Interview Questions

What Happens If a Test Method Throws an Exception?

JUnit Questions and Answers

(Continued from previous question...)

What Happens If a Test Method Throws an Exception?

If you write a test method that throws an exception by itself or by the method being tested, the JUnit runner will declare that this test fails.

The example test below is designed to let the test fail by throwing the uncaught IndexOutOfBoundsException exception:

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

// by
public class UnexpectedExceptionTest2 { 

  // throw any unexpected exception
  @Test public void testGet() throws Exception {
    ArrayList emptyList = new ArrayList();
    Exception anyException = null;

    // don't catch any exception
    Object o = emptyList.get(1);

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(UnexpectedExceptionTest2)
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
 at java.util.ArrayList.RangeCheck(
 at java.util.ArrayList.get(
 at UnexpectedExceptionTest2.testGet(UnexpectedExceptionTest2.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