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 Assert.fail().

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 FYICenter.com
public class UnexpectedExceptionTest1 { 
  @Test public void testGet() {
    ArrayList emptyList = new ArrayList();

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

  }
}


If you run this test, it will fail:

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

JUnit version 4.4
.E
Time: 0.015
There was 1 failure:
1) testGet(UnexpectedExceptionTest1)
java.lang.AssertionError: Unexpected exception
 at org.junit.Assert.fail(Assert.java:74)
 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(Method.java:597)
 at org.junit.internal.runners.TestMethod.invoke(TestMethod.java
 at org.junit.internal.runners.MethodRoadie.runTestMethod(Method
 at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.j
 at org.junit.internal.runners.MethodRoadie.runBeforesThenTestTh
 at org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie
 at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.jav
 at org.junit.internal.runners.JUnit4ClassRunner.invokeTestMetho
 at org.junit.internal.runners.JUnit4ClassRunner.runMethods(JUni
 at org.junit.internal.runners.JUnit4ClassRunner$1.run(JUnit4Cla
 at org.junit.internal.runners.ClassRoadie.runUnprotected(ClassR
 at org.junit.internal.runners.ClassRoadie.runProtected(ClassRoa
 at org.junit.internal.runners.JUnit4ClassRunner.run(JUnit4Class
 at org.junit.internal.runners.CompositeRunner.runChildren(Compo
 at org.junit.internal.runners.CompositeRunner.run(CompositeRunn
 at org.junit.runner.JUnitCore.run(JUnitCore.java:130)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:109)
 at org.junit.runner.JUnitCore.run(JUnitCore.java:100)
 at org.junit.runner.JUnitCore.runMain(JUnitCore.java:81)
 at org.junit.runner.JUnitCore.main(JUnitCore.java:44)

FAILURES!!!
Tests run: 1,  Failures: 1

(Continued on next question...)

Other Interview Questions