jantox
jantox

Reputation: 2185

Adding Test to TestSuite in JUnit4

Is there a way to programmatically add test to a testsuite in JUnit4?

In Junit3 you can do this

TestSuite ts = new TestSuite();
ts.addTestSuite(a.class);
ts.addTestSuite(b.class);

How bout in JUnit4?

Upvotes: 1

Views: 994

Answers (1)

Matthew Farwell
Matthew Farwell

Reputation: 61705

One way is to use Request#classes():

public static void main(String[] args) throws Exception {
    Request request = Request.classes(new Class<?>[] {Test1.class, Test2.class});

    JUnitCore jUnitCore = new JUnitCore();
    RunListener listener = new RunListener() {

        @Override
        public void testFailure(Failure failure) throws Exception {
            System.out.println("failure=" + failure);
        }

    };
    jUnitCore.addListener(listener);
    jUnitCore.run(request);
}

In the RunListener, you can override more than just testFailure.

If you want your tests to be more integrated into your build, then extend Suite

public static class DynamicSuite extends Suite {
    public DynamicSuite(Class<?> klass, RunnerBuilder builder) throws InitializationError {
        super(builder, klass, new Class<?>[] {Test1.class, Test2.class});
    }
}

The constructor that you use depends upon how the Suite is invoked. The above works in Eclipse.

Then just annotate an empty class with @RunWith(DynamicSuite.class):

@RunWith(DynamicSuite.class)
public class DynamicTestSuite {
}

Upvotes: 1

Related Questions