How to programmatically execute a test suite using JUnit4?

那年仲夏 提交于 2019-11-29 18:06:48

问题


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.


回答1:


Just specify the name of the suite class to JUnitCore:

Computer computer = new Computer();

JUnitCore jUnitCore = new JUnitCore();
jUnitCore.run(computer, MySuite.class);



回答2:


You can also that using command prompt as

java org.junit.runner.JUnitCore test class name



来源:https://stackoverflow.com/questions/10127052/how-to-programmatically-execute-a-test-suite-using-junit4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!