tyrondis
tyrondis

Reputation: 3494

Run a test case multiple times with different @BeforeClass setups in JUnit 4

I have a test case that looks like so:

public class MyTest {

    private static TestObject obj;

    @BeforeClass
    public static void setUpBeforeClass() {
        obj = new TestObject();
    }

    @Test
    public void testOne() {
        assertTrue(obj.hasFoo());
    }

    @Test
    public void testTwo() {
        assertEquals(42, obj.getBar());
    }

    // More tests here...

}

What I want to do now is running the whole test case with different instances of TestObject. So let's say I have 10 different TestObject instances. Now I want to run testOne() testTwo() and so on 10 times (with every instance of TestObject I need).

How can I achieve this with JUnit4? Or is my design bad? Any ideas for a better one?

Upvotes: 3

Views: 2094

Answers (3)

Holly Cummins
Holly Cummins

Reputation: 11482

You could achieve something close to this with inheritance, which would also have the advantage of allowing you to distinguish the test cases in your test output. You'll have to play around a bit, since statics and inheritance don't work so well together.

One option is to create your ten subclasses, each with a @Before method which initialises an instance obj field in the superclass. If you don't want the overhead of re-initialising a TestObject each time, you could also have an @BeforeClass method which initialises a singleton static classObj field. Your @Before would then just copy classObj to obj. Either way, your superclass has the test methods and the obj instance method, but no initialisation code.

Upvotes: 0

axtavt
axtavt

Reputation: 242686

Use parameterized test:

@RunWith(Parameterized.class)
public class MyTest {
    public MyTest(TestObject obj) {
        this.obj = obj;
    }

    @Parameters
    public static Collection<TestObject> params() { ... }

    ...
}

Upvotes: 5

Edwin Dalorzo
Edwin Dalorzo

Reputation: 78579

How about using an array to test everything?

public class MyTest {

    private static TestObject[] objs;

    @BeforeClass
    public static void setUpBeforeClass() {
        objs = new TestObj[]{new TestObject1(), new TestObject2()];
    }

    @Test
    public void testOne() {
        for(TestObject obj : objs){
           assertTrue(obj.hasFoo());
        }
    }

    @Test
    public void testTwo() {
        for(TestObject obj : objs) {
           assertEquals(42, obj.getBar());
        }
    }

    // More tests here...

}

Upvotes: 0

Related Questions