views:

22

answers:

2

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.

A: 

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.
manuel aldana
static{} initializer worked like a charm. Thanks!
zengr
A: 

Similar to manuel's point: do you -need- to use JUnit 3? Then a class-level static{} initializer might be your best bet.

Otherwise, I recommend using JUnit 4, which has a construct which would might enjoy:

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;


public class xxxxxTest  {

    @BeforeClass
    public static void beforeClass() {
        //Some init which i need only once
    }

    @Test
    public void testMyFirstMethodTest() {
        Assert.assertNotNull("");//do stuff here);
    }
}
The Alchemist