使用assertThrows测试抛出的异常是否有效,但我也希望使用ExpectedException测试异常消息,但即使使用相同的异常,它也不能工作,为什么?
工作代码:
@Test
void test() {
Assertions.assertThrows(
MyCustomException.class,
() -> methodBeingTested()); // passes
}有问题的代码:
@Rule
public ExpectedException expectedException = ExpectedException.none();
@Test
void test() {
expectedException.expect(MyCustomException.class);
methodBeingTested(); // fails
}日志:
package.MyCustomException: message.
at [...]
Caused by: anotherPackage.AnotherException: Exception Message
at [...]
... 68 more
Process finished with exit code -1发布于 2022-06-02 12:15:22
正如Thomas在评论中指出的那样,我使用了两种不同版本的JUnit (4和5),它们不能像我想的那样工作。
我的解决方案是使用assertThrows,将它分配给一个变量,并在该变量上断言消息,仅依赖于JUnit5。
Exception exception = assertThrows(
MyException.class,
() -> myMethod());
assertEquals("exception message", exception.getMessage());https://stackoverflow.com/questions/72467220
复制相似问题