AssertUtils.java 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package cn.iocoder.dashboard.util;
  2. import cn.hutool.core.util.ArrayUtil;
  3. import cn.hutool.core.util.ReflectUtil;
  4. import cn.iocoder.dashboard.common.exception.ErrorCode;
  5. import cn.iocoder.dashboard.common.exception.ServiceException;
  6. import org.junit.jupiter.api.Assertions;
  7. import java.lang.reflect.Field;
  8. import java.util.Arrays;
  9. /**
  10. * 单元测试,assert 断言工具类
  11. *
  12. * @author 芋道源码
  13. */
  14. public class AssertUtils {
  15. /**
  16. * 比对两个对象的属性是否一致
  17. *
  18. * 注意,如果 expected 存在的属性,actual 不存在的时候,会进行忽略
  19. *
  20. * @param expected 期望对象
  21. * @param actual 实际对象
  22. * @param ignoreFields 忽略的属性数组
  23. */
  24. public static void assertPojoEquals(Object expected, Object actual, String... ignoreFields) {
  25. Field[] expectedFields = ReflectUtil.getFields(expected.getClass());
  26. Arrays.stream(expectedFields).forEach(expectedField -> {
  27. // 如果是忽略的属性,则不进行比对
  28. if (ArrayUtil.contains(ignoreFields, expectedField.getName())) {
  29. return;
  30. }
  31. // 忽略不存在的属性
  32. Field actualField = ReflectUtil.getField(actual.getClass(), expectedField.getName());
  33. if (actualField == null) {
  34. return;
  35. }
  36. // 比对
  37. Assertions.assertEquals(
  38. ReflectUtil.getFieldValue(expected, expectedField),
  39. ReflectUtil.getFieldValue(actual, actualField),
  40. String.format("Field(%s) 不匹配", expectedField.getName())
  41. );
  42. });
  43. }
  44. /**
  45. * 比对抛出的 ServiceException 是否匹配
  46. *
  47. * @param errorCode 错误码对象
  48. * @param serviceException 业务异常
  49. */
  50. public static void assertPojoEquals(ErrorCode errorCode, ServiceException serviceException) {
  51. Assertions.assertEquals(errorCode.getCode(), serviceException.getCode(), "错误码不匹配");
  52. Assertions.assertEquals(errorCode.getMessage(), serviceException.getMessage(), "错误提示不匹配");
  53. }
  54. }