有没有办法在使用 AssertJ 时再次抛出异常来检查原因中的消息是否等于某个字符串。
我目前正在做类似的事情:
assertThatThrownBy(() -> SUT.method())
.isExactlyInstanceOf(IllegalStateException.class)
.hasRootCauseExactlyInstanceOf(Exception.class);
并想添加一个断言来检查根本原因中的消息。
有没有办法在使用 AssertJ 时再次抛出异常来检查原因中的消息是否等于某个字符串。
我目前正在做类似的事情:
assertThatThrownBy(() -> SUT.method())
.isExactlyInstanceOf(IllegalStateException.class)
.hasRootCauseExactlyInstanceOf(Exception.class);
并想添加一个断言来检查根本原因中的消息。
不完全是,你目前能做的最好的就是使用hasStackTraceContaining
, 例如
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).hasCauseInstanceOf(Exception.class)
.hasStackTraceContaining("no way")
.hasStackTraceContaining("you shall not pass");
从 AssertJ 3.16 开始,有两个新选项可用:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).getCause()
.hasMessage("you shall not pass");
Throwable rootCause = new RuntimeException("go back to the shadow!");
Throwable cause = new Exception("you shall not pass", rootCause);
Throwable runtime = new RuntimeException("no way", cause);
assertThat(runtime).getRootCause()
.hasMessage("go back to the shadow!");
从 AssertJ 3.14 开始,可以使用extracting
with :InstanceOfAssertFactory
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).extracting(Throwable::getCause, as(THROWABLE))
.hasMessage("you shall not pass");
as()
是从静态导入org.assertj.core.api.Assertions
和THROWABLE
从 静态导入的org.assertj.core.api.InstanceOfAssertFactories
。