How to programmatically run a test suite using JUnit4?

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

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

But is there a way to run the whole package using the Java API, for example using JUnitCore?

For example, you can run a test 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, so the following code works:

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

But I'm not sure if this is the recommended approach or if there is a flaw in writing the above code.

+10
junit junit4 automated-tests test-suite
source share
2 answers

Just provide the package class name for JUnitCore:

 Computer computer = new Computer(); JUnitCore jUnitCore = new JUnitCore(); jUnitCore.run(computer, MySuite.class); 
+12
source share

You can also use the command line as

java org.junit.runner.JUnitCore name of the test class

+4
source share

All Articles