How do I implement a test case for a thrown exception?
Created May 7, 2012
Erik Meade
Catch the
exception and if it isn't thrown call the fail method. Fail signals
the
failure of a test case. Here is an example:
1) make your TestCase class a subclass of ExceptionTestCase.
2) write the test ignoring exceptions
Test t= new ExceptionTestCase("testIndexOutOfBoundsException", ArrayIndexOutOfBoundsException.class)
public void testIndexOutOfBoundsException() {or use the ExceptionTestCase as follows.
Vector v= new Vector(10)
try {
Object o= v.elementAt(v.size());
fail("Should raise an ArrayIndexOutOfBoundsException");
} catch (ArrayIndexOutOfBoundsException e) {
}
}
1) make your TestCase class a subclass of ExceptionTestCase.
2) write the test ignoring exceptions
public void testIndexOutOfBoundsException() {3) create the TestCase:
Vector v= new Vector(10);
v.elementAt(v.size());
}
Test t= new ExceptionTestCase("testIndexOutOfBoundsException", ArrayIndexOutOfBoundsException.class)
Looking at this again, the first way is simpler. Sigh...