是否可以在单个 JUnit 单元测试中测试多个异常?我知道一个可以使用的异常(exception),例如
@Test(expected=IllegalStateException.class)
现在,如果我想测试另一个异常(比如 NullPointerException),可以在同一个注解中完成,还是在不同的注解中完成,还是我需要完全编写另一个单元测试?
最佳答案
你真的希望测试做一件事,并为此进行测试。如果您不确定要抛出哪个异常,那听起来对我来说不是一个好的测试。
例如(伪代码)
try {
badOperation();
/// looks like we succeeded. Not good! Fail the test
fail();
}
catch (ExpectedException e) {
// that's fine
}
catch (UnexpectedException e) {
// that's NOT fine. Fail the test
}
因此,如果您想测试您的方法是否会引发 2 个不同的异常(针对 2 组输入),那么您将需要 2 个测试。
关于java - 使用 JUnit 4 注释测试多个异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1410172/