java AssertJ在原因消息上Assert

ruarlubt  于 2023-01-07  发布在  Java
关注(0)|答案(2)|浏览(122)

当使用AssertJ处理一个抛出异常的方法时,是否有办法检查原因中的消息是否等于某个字符串?
我目前正在做的事情如下:

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

并且想要添加Assert以检查根本原因中的消息。

p5cysglq

p5cysglq1#

不完全是这样,目前最好的方法是使用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");
pu82cl6c

pu82cl6c2#

自AssertJ 3.16起,提供了两个新选项:

  • getCause()
Throwable runtime = new RuntimeException("no way", 
                                         new Exception("you shall not pass"));

assertThat(runtime).getCause()
                   .hasMessage("you shall not pass");
  • getRootCause()
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可以与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静态导入的。

相关问题