代码

  1. @NoArgsConstructor(access = AccessLevel.PRIVATE)
  2. public final class Assert {
  3. public static void greaterThan(double num, double exp, String msg) {
  4. if (num < exp) {
  5. throw new IllegalArgumentException(msg);
  6. }
  7. }
  8. public static void notNull(Object object, String msg) {
  9. if (null == object) {
  10. throw new IllegalArgumentException(msg);
  11. }
  12. }
  13. public static void notEmpty(String str, String msg) {
  14. if (null == str || "".equals(str)) {
  15. throw new IllegalArgumentException(msg);
  16. }
  17. }
  18. public static <T> void notEmpty(T[] arr, String msg) {
  19. if (null == arr || arr.length == 0) {
  20. throw new IllegalArgumentException(msg);
  21. }
  22. }
  23. public static <T> T wrap(Callable<T> callable) {
  24. try {
  25. return callable.call();
  26. } catch (Exception e) {
  27. throw new RuntimeException(e);
  28. }
  29. }
  30. public static void packageNotEmpty(Class<?> clazz,String msg){
  31. if (clazz.getPackage() == null) {
  32. throw new IllegalArgumentException("[" + clazz.getName() + ".java] " + msg);
  33. }
  34. }
  35. }

测试

  1. import org.junit.Test;
  2. public class AssertTest {
  3. @Test(expected = IllegalArgumentException.class)
  4. public void testNotEmpty() {
  5. Assert.notEmpty("", "Not Empty");
  6. Assert.notEmpty(new String[]{}, "Arr Empty");
  7. Assert.notNull(null, "Not null");
  8. }
  9. @Test(expected = RuntimeException.class)
  10. public void testWrap() {
  11. Assert.wrap(() -> {
  12. int a = 1 / 0;
  13. return true;
  14. });
  15. }
  16. @Test
  17. public void testWrap2() {
  18. boolean flag = Assert.wrap(() -> true);
  19. org.junit.Assert.assertEquals(true, flag);
  20. }
  21. }