Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class teardown in junit 3?

Tags:

java

junit

junit4

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?

like image 670
Cincinnati Joe Avatar asked Oct 29 '09 21:10

Cincinnati Joe


2 Answers

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 ");
        }
    };
}
like image 130
Cincinnati Joe Avatar answered Sep 26 '22 07:09

Cincinnati Joe


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.

like image 34
Dónal Avatar answered Sep 23 '22 07:09

Dónal