Interview Questions

How Do You Test an Unexpected Exception with JUnit?

JUnit Questions and Answers

(Continued from previous question...)

How Do You Test an Unexpected Exception with JUnit?

If you want to test a method that could raise an unexpected exception, you should design a test that:

  • Put the test code inside a "try" block".
  • Catch any unexpected exception object.
  • Fail the test witl

JUnit runner will fail this test if the test code raised any unexpected exception.

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

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

// by
public class UnexpectedExceptionTest1 { 
  @Test public void testGet() {
    ArrayList emptyList = new ArrayList();

    // catch any unexpected exception
    try {
       Object o = emptyList.get(1);
    } catch (Exception e) {"Unexpected exception");


If you run this test, it will fail:

java -cp .;junit-4.4.jar org.junit.runner.JUnitCore 

JUnit version 4.4
Time: 0.015
There was 1 failure:
1) testGet(UnexpectedExceptionTest1)
java.lang.AssertionError: Unexpected exception
 at UnexpectedExceptionTest1.testGet(UnexpectedExceptionTest1.ja
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAcce
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMe
 at java.lang.reflect.Method.invoke(
 at org.junit.internal.runners.TestMethod.invoke(
 at org.junit.internal.runners.MethodRoadie.runTestMethod(Method
 at org.junit.internal.runners.MethodRoadie$
 at org.junit.internal.runners.MethodRoadie.runBeforesThenTestTh
 at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie
 at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMetho
 at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUni
 at org.junit.internal.runners.JUnit4ClassRunner$
 at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassR
 at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoa
 at org.junit.internal.runners.CompositeRunner.runChildren(Compo
 at org.junit.runner.JUnitCore.runMain(
 at org.junit.runner.JUnitCore.main(

Tests run: 1,  Failures: 1

(Continued on next question...)

Other Interview Questions