You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:24:02