White Box Testing
Test your code
   Home      JUnit4-Exception-Testing
 

JUnit4 Exception Testing

We can test for exceptions in JUnit4 by following ways
 
1) @Test(expected=IllegalArgumentException.class) pass if the method throws the named exception and fails if the different exception thrown or test method does not throw an exception.
@Test(expected = ArithmeticException.class)

public void exceptionTest() {

            Calculator cal = new Calculator();

            cal.divide(1, 0);

}

 

2) try-catch idiom as we use in junit3

@Test

public void exceptionTest() {

      try {

            Calculator cal = new Calculator();

            cal.divide(1, 0);

            fail("Expected an ArithmeticException to be thrown");

      }catch (ArithmeticException e) {

      }

}          

 

3) ExpectedException Rule tells you expected exception message along with expected exception
 

@Rule

public ExpectedException thrown = ExpectedException.none();

 

@Test

public void exceptionTest throws() {

     

      Calculator cal = new Calculator();

      cal.divide(1, 0);

      thrown.expect(ArithmeticException.class);

      thrown.expectMessage("Divide by zero exception");

      //execution never reach there

}