开发者

Junit exception handling

I want to know that whether this test case should pass or fail beacause expected = Ind开发者_如何学JAVAexOutOfBoundsException.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) {

        }   

}


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:

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


It should fail because it doesn't throw any exception; the ArithmeticException is caught and swallowed by the catch block.


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:

@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();
}

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜