Interview Questions

How Do You Test an Expected Exception with JUnit?

JUnit Questions and Answers

(Continued from previous question...)

How Do You Test an Expected Exception with JUnit?

If you want to test a method that will throw an exception under a specific condition, you can:

  • Put the test code inside a "try" block".
  • Catch the expected exception object.
  • Assert the exception object with Assert.assertNotNull().

JUnit runner will fail this test if the test code did not raise the expected exception.

Here is a good test class that test the expected IndexOutOfBoundsException exception raised by the get() method of the ArrayList class:

import org.junit.*;
import java.util.*;

// by
public class ExpectedExceptionTest1 { 
  @Test public void outOfBounds() {
    ArrayList emptyList = new ArrayList();
    Exception eOutOfBounds = null;
    // catch the expected exception
    try {
       Object o = emptyList.get(1);
    } catch (IndexOutOfBoundsException e) {
       eOutOfBounds = e;
    // asset the exception object
    Assert.assertNotNull("No expected exception", eOutOfBounds);

But there a better way to test the expected exception provided by the JUnit @Test annotation. See the next question.

(Continued on next question...)

Other Interview Questions