Search code examples
unit-testingjunitinstallationtest-suite

Execute setup() once workaround causing TestSuit to fail


I have 2 files:

xxxxxTest.java [refer this]

public class xxxxxTest extends TestCase {

    // Run setup only once
    public static Test suite() {
        TestSetup setup = new TestSetup(new TestSuite(xxxxxTest.class)) {
            protected void setUp() throws Exception {
              //Some init which i need only once
            }

            protected void tearDown() throws Exception {

            }
        };
        return setup;
    }

    public void testMyFirstMethodTest() {
        assertNotNull(do stuff here);
    }
}

AllTests.java

public class AllTests {
    public static Test suite() {
        TestSuite suite = new TestSuite("Test for xxxxxx");
        //$JUnit-BEGIN$
        suite.addTestSuite(xxxxxTest.class);
        //$JUnit-END$
        return suite;
    }
}

So, my individual test(xxxxxTest.java) works fine, exactly as I want.When i run my test suite (AllTests.java), it fails, because the init in setup() i provided in xxxxxTest.java are not being executed.

Any suggestions?

UPDATE

I tried @BeforeClass in JUnit 4. But, it didn't help because in my ssetUp() method, I start an embedded Jetty server (server.start()), the server works fine with the code I posted, but when I do the same with @BeforeClass, it does not work.


Solution

  • In rare cases I also hacked around with static when using JUnit3.

    In your case:

    • give the static{} initializer a try, maybe it works opposed to your static initialization.
    • if possible upgrade to JUnit4 and use @BeforeClass annotation (it is run once for a test-class). Your other JUnit3 test-classes should be runnable with JUnit4 test-runner also.