在eclipse中,使用JUnit 4,您可以右键单击项目或包,然后单击Run as JUnit Test,它将运行该分组中的所有JUnit测试。有没有办法在代码中做同样的事情?
答案 0 :(得分:8)
您可以在junit中使用包,例如JUnitCore,如下所示:
public static void main(String[] args){
List tests = new ArrayList();
tests.add(TestOne.class);
tests.add(TestTwo.class);
for (Class test : tests){
runTests(test);
}
}
private static void runTests(Class test){
Result result = JUnitCore.runClasses(test);
for (Failure failure : result.getFailures()){
System.out.println(failure.toString());
}
}
答案 1 :(得分:6)
使用JUnit Suite:
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
// Put your Test Case Class here
@Suite.SuiteClasses({
JunitTest1.class,
JunitTest2.class,
JunitTest3.class
})
public class JunitTestSuite {}
然后创建一个运行它的主方法。
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class JunitTestSuiteRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(JunitTestSuite.class);
for (Failure fail : result.getFailures()) {
System.out.println(fail.toString());
}
if (result.wasSuccessful()) {
System.out.println("All tests finished successfully...");
}
}}
答案 2 :(得分:1)
JUnit提供test Suite。试一试。
[...]
public class TestCaseA {
@Test
public void testA1() {
// omitted
}
}
[...]
public class TestCaseB {
@Test
public void testB1() {
// omitted
}
}
[...]
@RunWith(value=Suite.class)
@SuiteClasses(value = {TestCaseA.class})
public class TestSuiteA {
}
[...]
@RunWith(value=Suite.class)
@SuiteClasses(value = {TestCaseB.class})
public class TestSuiteB {
}
[...]
@RunWith(value = Suite.class )
@SuiteClasses(value = {TestSuiteA.class, TestSuiteB.class})
public class MasterTestSuite{
}