是否可以在单个JUnit单元测试中测试多个异常?我知道有一个例外可以使用,例如
@Test(expected=IllegalStateException.class)
现在,如果我想测试另一个异常(比如NullPointerException),是否可以在相同的注释、不同的注释中完成这项工作,或者我是否需要完全编写另一个单元测试?
发布于 2009-09-11 10:56:25
你真的想让测试一个并对其进行测试。如果您不确定将抛出哪个异常,那么对我来说,这听起来不是一个好的测试。
例如(伪代码)
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
}
因此,如果你想测试你的方法抛出了两个不同的异常(对于两组输入),那么你需要两个测试。
发布于 2009-09-19 21:36:05
对于注释,这是不可能的。
在JUnit 4.7中,您可以使用新的ExpectedException
规则
public static class HasExpectedException {
@Interceptor
public ExpectedException thrown= new ExpectedException();
@Test
public void throwsNothing() {
}
@Test
public void throwsNullPointerException() {
thrown.expect(NullPointerException.class);
throw new NullPointerException();
}
@Test
public void throwsNullPointerExceptionWithMessage() {
thrown.expect(NullPointerException.class);
thrown.expectMessage("happened?");
throw new NullPointerException("What happened?");
}
}
更多信息请参阅
如果您无法更新到JUnit 4.7,则必须编写表单的裸单元测试
public test() {
try {
methodCall(); // should throw Exception
fail();
}
catch (Exception ex) {
assert((ex instanceof A) || (ex instanceof B) || ...etc...);
...
}
}
发布于 2017-09-13 19:46:35
虽然这在JUnit 4中是不可能的,但它是如果您切换到TestNG,这是可能的,它允许您编写
@Test(expectedExceptions = {IllegalArgumentException.class, NullPointerException.class})
https://stackoverflow.com/questions/1410172
复制相似问题