user24877
user24877

Reputation: 155

How do you customize exception handling behavior in JUnit 3?

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?

Upvotes: 3

Views: 3324

Answers (3)

rwitzel
rwitzel

Reputation: 1818

There is no need to implement your own solution because there is already one that can be used with JUnit3 (and any other testing framework): catch-exception.

Upvotes: 2

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147154

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.

Upvotes: 1

Kosi2801
Kosi2801

Reputation: 23095

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.

Upvotes: 9

Related Questions