Junit异常处理
我想知道这个测试用例应该通过还是失败 因为 预期 = IndexOutOfBoundsException.class 实际上它正在抛出算术异常。谁能解释一下吗?
@Test(expected = IndexOutOfBoundsException.class)
public void testDivideNumbers()throws ArithmeticException{
try{
double a = 10/0;
fail("Failed: Should get an Arithmatic Exception");
}
catch (ArithmeticException e) {
}
}
I want to know that whether this test case should pass or fail
beacause
expected = IndexOutOfBoundsException.class
and actually it is throwing Arithmatic exception. can anyone explain?
@Test(expected = IndexOutOfBoundsException.class)
public void testDivideNumbers()throws ArithmeticException{
try{
double a = 10/0;
fail("Failed: Should get an Arithmatic Exception");
}
catch (ArithmeticException e) {
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
要测试是否抛出正确的异常,您不应让测试方法抛出异常,而应让测试本身导致抛出的异常。
因此,如果预期出现 ArithmeticException,则测试应该是:
To test that the correct exception is thrown you should not have the test method throw the exception but just have the test itself result in the thrown exception.
So if ArithmeticException is expected then the test should be:
它应该失败,因为它不会抛出任何异常; ArithmeticException 被
catch
块捕获并吞掉。It should fail because it doesn't throw any exception; the ArithmeticException is caught and swallowed by the
catch
block.此测试预计会抛出 IndexOutOfBoundsException。因为测试中没有发生这种情况,所以测试失败。您可以像这样“修复”测试:
您不应将 catch 块留空。您应该始终在其中添加一些断言,以证明失败()没有发生并且捕获确实发生,并且重要的是,由于您期望的原因而发生。
This test is expecting to get an IndexOutOfBoundsException thrown. Because that does not happen in the test, the test fails. You can "fix" the test like this:
You should not leave the catch block empty. You should always put some assert in it proving that the fail() didn't happen and the catch did happen and, importantly, happened for the reason you expected.