How do I implement a test case for a thrown exception?

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:

public void testIndexOutOfBoundsException() {
    Vector v= new Vector(10)
    try {
         Object o= v.elementAt(v.size());
         fail("Should raise an ArrayIndexOutOfBoundsException");
    } catch (ArrayIndexOutOfBoundsException e) {
    }
}
or use the ExceptionTestCase as follows.
1) make your TestCase class a subclass of ExceptionTestCase.
2) write the test ignoring exceptions
public void testIndexOutOfBoundsException() {
    Vector v= new Vector(10);
    v.elementAt(v.size());
}
3) create the TestCase:
    Test t= new ExceptionTestCase("testIndexOutOfBoundsException", ArrayIndexOutOfBoundsException.class)

Looking at this again, the first way is simpler. Sigh...

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact