views:

779

answers:

2

I want to implement exception checking (like in JUnit 4) using JUnit 3. For example, I would like to be able to write tests like this:

public void testMyExceptionThrown() throws Exception {
    shouldThrow(MyException.class);

    doSomethingThatMightThrowMyException();
}

This should succeed if and only if a MyException is thrown. There is the ExceptionTestCase class in JUnit, but but I want something that each test* method can decide to use or not use. What is the best way to achieve this?

+5  A: 

Would the solution:

public void testMyExceptionThrown() throws Exception {
    try {
      doSomethingThatMightThrowMyException();
      fail("Expected Exception MyException");
    } catch(MyException e) {
      // do nothing, it's OK
    }
}

be suitable for what you're thinking of?

Also have a look at this thread, where someone created a Proxy-solution for JUnit3 which seems to be another possibility to solve your problem.

Kosi2801
+1  A: 

The simplest approach is to use the Execute Around idiom to abstract away the try-catch that you would usually write.

More sophisticated is to note that TestCase is just a Test. I forget the details, but we can override the execution of the test (which the framework initially calls through run(TestResult) specified in Test). In that override we can place the try-catch, as per Execute Around. The testXxx method should call a set method to install the expected exception type.

Tom Hawtin - tackline