tags:

views:

662

answers:

2

We have a lot of integration tests written using JUnit 3, though we're now running them with 4.4. A few of these have a need for a tearDown method that runs after all the tests in the class are complete (to free some common resources).

I see that this can be done in junit 4 with @AfterClass (org.junit). However, mixing this into existing junit 3 tests that extend TestCase (junit.framework.*) doesn't seem to work. [BTW is there a migration tool yet? Question 264680 indicated there wasn't one a year ago.]

I've seen mention of using junit.extensions.TestSetup for this kind of thing. My brief testing of this didn't seem work. Any examples?

+3  A: 

In JUnit 4, your test class doesn't need to extend TestCase. Instead you must ensure that the name of your test class matches *Test and each test method is annotated with @Test. Have you tried making these changes, then adding the @AfterClass annotation to the relevant method?

There are annotations to replace most/all functionality you may currently be using from TestCase.

Don
In parallel to trying to get a class-wide teardown, I'm also trying to just convert one class to junit 4 annotations. Not having much luck yet as Eclipse/command-line then thinks I don't have any tests to be run.
Cincinnati Joe
I've updated my answer, the advice I gave previously was completely wrong and I deserve to have been downvoted to hell. Please follow the instructions above and try again.
Don
+1  A: 

Found the answer to my own question :) I had tried this briefly before posting my question, but it wasn't working for me. But I realize now that it's because our test framework is invoking junit differently than the default, so it wasn't calling the "suite" method that is needed in the following solution. In Eclipse, if I use the bundled junit runner to directly execute one Test/TestCase, it runs fine.

A way to do this setup/teardown once per class in junit 3 is to use TestSuite. Here's an example on junit.org:

Is there a way to make setUp() run only once?

public static Test suite() {
    return new TestSetup(new TestSuite(YourTestClass.class)) {

        protected void setUp() throws Exception {
            System.out.println(" Global setUp ");
        }
        protected void tearDown() throws Exception {
            System.out.println(" Global tearDown ");
        }
    };
}
Cincinnati Joe