pha*_*99w 26 java junit exception
是否可以在单个JUnit单元测试中测试多个异常?例如,我知道可以使用一个例外
    @Test(expected=IllegalStateException.class)
现在,如果我想测试另一个异常(例如,NullPointerException),可以在相同的注释,不同的注释中完成吗,还是我需要完全编写另一个单元测试?
Bri*_*new 23
你真的希望测试做一件事,并测试它.如果你不确定将抛出哪个异常,那对我来说听起来不是一个好的测试.
例如(伪代码)
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个测试.
aku*_*uhn 12
注释无法做到这一点.
使用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...);
        ...
    }
}
虽然这在 JUnit 4 中是不可能的,但是如果您切换到 TestNG,它允许您编写
@Test(expectedExceptions = {IllegalArgumentException.class, NullPointerException.class})
| 归档时间: | 
 | 
| 查看次数: | 41394 次 | 
| 最近记录: |