sti*_*kku 3 java testing unit-testing assertj
有没有办法在使用AssertJ时再次抛出一个方法来检查原因中的消息是否等于某个字符串.
我目前正在做类似的事情:
assertThatThrownBy(() -> SUT.method())
.isExactlyInstanceOf(IllegalStateException.class)
.hasRootCauseExactlyInstanceOf(Exception.class);
Run Code Online (Sandbox Code Playgroud)
并且想添加一个断言来检查根本原因中的消息.
不完全是,目前你能做的最好的就是使用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");
Run Code Online (Sandbox Code Playgroud)
自 AssertJ 3.16 起,有两个新选项可用:
Throwable runtime = new RuntimeException("no way",
new Exception("you shall not pass"));
assertThat(runtime).getCause()
.hasMessage("you shall not pass");
Run Code Online (Sandbox Code Playgroud)
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!");
Run Code Online (Sandbox Code Playgroud)
自 AssertJ 3.14 起,可以使用extractingwith 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");
Run Code Online (Sandbox Code Playgroud)
as()静态导入自org.assertj.core.api.Assertions和THROWABLE静态导入自org.assertj.core.api.InstanceOfAssertFactories.