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