user707299
user707299

Reputation: 21

Junit exception handling

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) {

        }   

}

Upvotes: 2

Views: 10406

Answers (3)

striker77
striker77

Reputation: 552

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;
}

Upvotes: 4

alpian
alpian

Reputation: 4748

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.

Upvotes: 1

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81724

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

Upvotes: 1

Related Questions