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 FYICenter.com
public class UnexpectedExceptionTest2 {
// throw any unexpected exception
@Test public void testGet() throws Exception {
ArrayList emptyList = new ArrayList
If you run this test, it will fail:
java -cp .;junit-4.4.jar org.junit.runner.JUnitCore
UnexpectedExceptionTest2
JUnit version 4.4
.E
Time: 0.015
There was 1 failure:
1) testGet(UnexpectedExceptionTest2)
java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.RangeCheck(ArrayList.java:547)
at java.util.ArrayList.get(ArrayList.java:322)
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(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