使用 junit 5 测试预期的异常消息
Testing for the expected exception message with junit 5
我有一个项目,我在其中进行测试,我故意造成问题,然后验证代码是否按照我想要的方式响应。为此,我想确保例外不仅是正确的 class,而且它们还必须传达正确的信息。
所以在 my existing (junit 4) tests 之一中,我有类似的东西:
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();
}
}
我目前正在考虑完全迁移到不再支持 @Rule and now has the assertThrows that seems to replace this 的 junit 5。
我一直无法弄清楚如何编写一个测试,不仅检查抛出的异常 (class),还检查附加到该异常的消息。
在 Junit 5 中编写此类测试的正确方法是什么?
感谢@michalk 和我的一位同事,这项工作成功了:
Exception expectedEx = assertThrows(MyCustomException.class, () ->
doStuffThatShouldFail()
);
assertTrue(expectedEx.getMessage().startsWith("Unable to load "));
assertTrue(expectedEx.getMessage().endsWith(" resources."));
由于 Assertions.assertThrows
returns 您的异常实例,您可以在返回的实例上调用 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
我有一个项目,我在其中进行测试,我故意造成问题,然后验证代码是否按照我想要的方式响应。为此,我想确保例外不仅是正确的 class,而且它们还必须传达正确的信息。
所以在 my existing (junit 4) tests 之一中,我有类似的东西:
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();
}
}
我目前正在考虑完全迁移到不再支持 @Rule and now has the assertThrows that seems to replace this 的 junit 5。
我一直无法弄清楚如何编写一个测试,不仅检查抛出的异常 (class),还检查附加到该异常的消息。
在 Junit 5 中编写此类测试的正确方法是什么?
感谢@michalk 和我的一位同事,这项工作成功了:
Exception expectedEx = assertThrows(MyCustomException.class, () ->
doStuffThatShouldFail()
);
assertTrue(expectedEx.getMessage().startsWith("Unable to load "));
assertTrue(expectedEx.getMessage().endsWith(" resources."));
由于 Assertions.assertThrows
returns 您的异常实例,您可以在返回的实例上调用 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