AssertUtils.java 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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 cn.iocoder.dashboard.common.exception.util.ServiceExceptionUtil;
  7. import org.junit.jupiter.api.Assertions;
  8. import org.junit.jupiter.api.function.Executable;
  9. import java.lang.reflect.Field;
  10. import java.util.Arrays;
  11. import static org.junit.jupiter.api.Assertions.assertThrows;
  12. /**
  13. * 单元测试,assert 断言工具类
  14. *
  15. * @author 芋道源码
  16. */
  17. public class AssertUtils {
  18. /**
  19. * 比对两个对象的属性是否一致
  20. *
  21. * 注意,如果 expected 存在的属性,actual 不存在的时候,会进行忽略
  22. *
  23. * @param expected 期望对象
  24. * @param actual 实际对象
  25. * @param ignoreFields 忽略的属性数组
  26. */
  27. public static void assertPojoEquals(Object expected, Object actual, String... ignoreFields) {
  28. Field[] expectedFields = ReflectUtil.getFields(expected.getClass());
  29. Arrays.stream(expectedFields).forEach(expectedField -> {
  30. // 如果是忽略的属性,则不进行比对
  31. if (ArrayUtil.contains(ignoreFields, expectedField.getName())) {
  32. return;
  33. }
  34. // 忽略不存在的属性
  35. Field actualField = ReflectUtil.getField(actual.getClass(), expectedField.getName());
  36. if (actualField == null) {
  37. return;
  38. }
  39. // 比对
  40. Assertions.assertEquals(
  41. ReflectUtil.getFieldValue(expected, expectedField),
  42. ReflectUtil.getFieldValue(actual, actualField),
  43. String.format("Field(%s) 不匹配", expectedField.getName())
  44. );
  45. });
  46. }
  47. /**
  48. * 执行方法,校验抛出的 Service 是否符合条件
  49. *
  50. * @param executable 业务异常
  51. * @param errorCode 错误码对象
  52. * @param messageParams 消息参数
  53. */
  54. public static void assertServiceException(Executable executable, ErrorCode errorCode, Object... messageParams) {
  55. // 调用方法
  56. ServiceException serviceException = assertThrows(ServiceException.class, executable);
  57. // 校验错误码
  58. Assertions.assertEquals(errorCode.getCode(), serviceException.getCode(), "错误码不匹配");
  59. String message = ServiceExceptionUtil.doFormat(errorCode.getCode(), errorCode.getMessage(), messageParams);
  60. Assertions.assertEquals(message, serviceException.getMessage(), "错误提示不匹配");
  61. }
  62. }