ExceptionTestCase.java revision 58a8b0aba2dec5695628a2bf25a3fae42c2c3533
1package junit.extensions;
2
3import junit.framework.TestCase;
4
5/**
6 * A TestCase that expects an Exception of class fExpected to be thrown.
7 * The other way to check that an expected exception is thrown is:
8 * <pre>
9 * try {
10 *   shouldThrow();
11 * }
12 * catch (SpecialException e) {
13 *   return;
14 * }
15 * fail("Expected SpecialException");
16 * </pre>
17 *
18 * To use ExceptionTestCase, create a TestCase like:
19 * <pre>
20 * new ExceptionTestCase("testShouldThrow", SpecialException.class);
21 * </pre>
22 */
23public class ExceptionTestCase extends TestCase {
24	Class fExpected;
25
26	public ExceptionTestCase(String name, Class exception) {
27		super(name);
28		fExpected= exception;
29	}
30	/**
31	 * Execute the test method expecting that an Exception of
32	 * class fExpected or one of its subclasses will be thrown
33	 */
34	protected void runTest() throws Throwable {
35		try {
36			super.runTest();
37		}
38		catch (Exception e) {
39			if (fExpected.isAssignableFrom(e.getClass()))
40				return;
41			else
42				throw e;
43		}
44		fail("Expected exception " + fExpected);
45	}
46}