10

I am trying to invoke a JUnit Test suite using the API. I know that you can suite up test classes using the following:

@RunWith(Suite.class)
@Suite.SuiteClasses({
  Test1.class,
  Test2.class, ...
})

But, is there a way to trigger the entire suite using the Java API, using JUnitCore for example?

For example, you can trigger a test by using the following code:

Runner r = 
try {
  r = new BlockJUnit4ClassRunner(Class.forName(testClass));
} catch (ClassNotFoundException | InitializationError e) {
  // handle
}
JUnitCore c = new JUnitCore();
c.run(Request.runner(r));

Update:

From the API, it seems that the Suite class itself is a runner, hence the following code seems to work:

Suite suite = new Suite(klass, new RunnerBuilder() {
... // Implement methods
});
JUnitCore c = new JUnitCore();
c.run(Request.runner(suite));

But I am not sure if this is a recommended approach or if there is any downside to writing the above code.

2 Answers 2

14

Just specify the name of the suite class to JUnitCore:

Computer computer = new Computer();

JUnitCore jUnitCore = new JUnitCore();
jUnitCore.run(computer, MySuite.class);
1
  • Thanks Matthew! I will definitely give this a try. In the meantime, do you have recommendations for the code snippet in my update?
    – Neel
    Commented Apr 16, 2012 at 14:13
4

You can also that using command prompt as

java org.junit.runner.JUnitCore test class name

2
  • 5
    I don't think that this qualifies as "programmatically".
    – oers
    Commented Apr 13, 2012 at 9:04
  • 1
    It will if you call it using runtime.exec Commented Apr 13, 2012 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.