7

有没有办法在使用 AssertJ 时再次抛出异常来检查原因中的消息是否等于某个字符串。

我目前正在做类似的事情:

assertThatThrownBy(() -> SUT.method())
            .isExactlyInstanceOf(IllegalStateException.class)
            .hasRootCauseExactlyInstanceOf(Exception.class);

并想添加一个断言来检查根本原因中的消息。

4

2 回答 2

12

不完全是,你目前能做的最好的就是使用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");
于 2016-08-15T10:39:09.553 回答
11

从 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 开始,可以使用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");

as()是从静态导入org.assertj.core.api.AssertionsTHROWABLE从 静态导入的org.assertj.core.api.InstanceOfAssertFactories

于 2020-02-06T11:16:55.713 回答