2011-04-28 84 views
2

我想知道这个测试用例应该合格还是不合格 因为 expected = IndexOutOfBoundsException.class 实际上它抛出了Arithmatic异常。谁能解释一下?Junit异常处理

@Test(expected = IndexOutOfBoundsException.class) 
public void testDivideNumbers()throws ArithmeticException{ 
    try{ 
     double a = 10/0; 
     fail("Failed: Should get an Arithmatic Exception"); 

     } 
    catch (ArithmeticException e) { 

     } 

} 

回答

1

它应该失败,因为它不会抛出任何异常; ArithmeticException被catch块捕获并吞噬。

1

这个测试是期望得到IndexOutOfBoundsException异常抛出。因为这在测试中不会发生,所以测试失败。您可以像这样“修复”测试:

@Test(expected = IndexOutOfBoundsException.class) 
public void testDivideNumbers() { 
    try { 
     double a = 10/0; 
     Assert.fail("Failed: Should get an Arithmetic Exception"); 
    } 
    catch (ArithmeticException e) { 
     // Assert that this exception is thrown as expected 
     Assert.assertEquals("/ by zero", e.getMessage()); 
    } 
    throw new IndexOutOfBoundsException(); 
} 

您不应该将catch块留空。你应该总是把一些断言它证明了失败()并没有发生和捕捉发生,重要的是,发生了你所期望的原因。

+0

预期= IndexOutOfBoundsException异常,我举办以及醒目的ArithmeticException所以有什么用@Test注解吗? – user707299 2011-04-29 07:44:46

4

要测试正确的异常被抛出,你不应该有测试方法抛出异常,但只是测试本身导致抛出的异常。

所以,如果ArithmeticException预期那么测试应该是:

@Test(expected = ArithmeticException.class) 
public void testDivideNumbers() { 
    double a = 10/0; 
}