【问题标题】:AssertJ assert on the cause messageAssertJ 断言原因消息
【发布时间】:2016-08-14 14:48:18
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java unit-testing testing assertj


    【解决方案1】:

    不完全是,目前你能做的最好的就是使用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");
    

    【讨论】:

    • 如果 Stefano Cordio 建议的版本 >= 3.16,请考虑使用 getCause()
    【解决方案2】:

    自 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 开始,可以使用 extractingInstanceOfAssertFactory

    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 静态导入的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-05
      • 2016-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多