使用 junit 5 测试预期的异常消息

Nie*_*jes 5 java junit junit4 junit5

我有一个项目,在那里我进行了测试,我故意造成问题,然后验证代码是否按我想要的方式响应。为此,我想确保异常不仅是正确的类,而且它们还必须携带正确的信息。

所以在我现有的(junit 4)测试之一中,我有类似的东西:

public class MyTests {
  @Rule
  public final ExpectedException expectedEx = ExpectedException.none();

  @Test
  public void testLoadingResourcesTheBadWay(){
    expectedEx.expect(MyCustomException.class);
    expectedEx.expectMessage(allOf(startsWith("Unable to load "), endsWith(" resources.")));
    doStuffThatShouldFail();
  }
}
Run Code Online (Sandbox Code Playgroud)

我目前正在考虑完全迁移到不再支持@Rule 的junit 5,现在有了似乎取代了这个assertThrows

我无法弄清楚如何编写一个不仅检查抛出的异常(类)而且还检查附加到该异常的消息的测试。

在 Junit 5 中编写此类测试的正确方法是什么?

mic*_*alk 11

由于Assertions.assertThrows返回您的异常实例,您可以getMessage在返回的实例上调用并对此消息进行断言:

Executable executable = () -> sut.method(); //prepare Executable with invocation of the method on your system under test

Exception exception = Assertions.assertThrows(MyCustomException.class, executable); // you can even assign it to MyCustomException type variable
assertEquals(exception.getMessage(), "exception message"); //make assertions here
Run Code Online (Sandbox Code Playgroud)


Nie*_*jes 7

感谢@michalk 和我的一位同事,这有效:

Exception expectedEx = assertThrows(MyCustomException.class, () ->
    doStuffThatShouldFail()
);
assertTrue(expectedEx.getMessage().startsWith("Unable to load "));
assertTrue(expectedEx.getMessage().endsWith(" resources."));
Run Code Online (Sandbox Code Playgroud)