AssertJ如何校验DataIntegrityViolationException根因的constraintName值
可行方案
AssertJ原生支持这种嵌套异常属性的校验,以下是几种常用实现方式:
方式1:类型安全写法(推荐)
通过方法引用提取约束名,编译期即可校验getter方法存在,避免硬编码字段名的拼写错误:
assertThatExceptionOfType(DataIntegrityViolationException.class) .isThrownBy(() -> xrepo.save(abc)) .cause() .isExactlyInstanceOf(ConstraintViolationException.class) .extracting(ConstraintViolationException::getConstraintName) .isEqualTo("XXXX");
方式2:属性名提取写法
如果你接受硬编码字段名,可以直接通过属性名提取校验:
assertThatExceptionOfType(DataIntegrityViolationException.class) .isThrownBy(() -> xrepo.save(abc)) .withCauseExactlyInstanceOf(ConstraintViolationException.class) .extracting(Throwable::getCause) .hasFieldOrPropertyWithValue("constraintName", "XXXX");
说明
你预想中的with方法并非AssertJ异常断言的原生方法,所以无法直接调用。核心逻辑是先通过cause()或者extracting(Throwable::getCause)切换到内层ConstraintViolationException的断言上下文,再做属性校验即可。
内容的提问来源于stack exchange,提问作者khmarbaise
相关产品推荐
相关产品推荐

