您可以使用JUnit的ParallelComputer
(注意它仍然被认为是实验性的)完成此操作。这是一个非常简单的实现,它由java.util.concurrent.ExecutorService API支持。
如果你好奇它是如何工作的,check out the source。
基本上,您可以拨打JUnitCore.runClasses(Computer, Classes ...)
并传入第一个参数的ParallelComputer
对象。
实例:
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
import org.junit.runner.JUnitCore;
public class ParallelComputerExample {
@Test
public void runAllTests() {
Class<?>[] classes = { ParallelTest1.class, ParallelTest2.class };
// ParallelComputer(true,true) will run all classes and methods
// in parallel. (First arg for classes, second arg for methods)
JUnitCore.runClasses(new ParallelComputer(true, true), classes);
}
public static class ParallelTest1 {
@Test
public void test1a() {
lookBusy(3000);
}
@Test
public void test1b() {
lookBusy(3000);
}
}
public static class ParallelTest2 {
@Test
public void test2a() {
lookBusy(3000);
}
@Test
public void test2b() {
lookBusy(3000);
}
}
public static void lookBusy(long ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
System.out.println("interrupted");
}
}
}
上面的代码将在3秒内,因为所有的方法和类并行地运行运行。
这将运行在6s(因为所有的类都是并行的)。 JUnitCore.runClasses(new ParallelComputer(true, false), classes);
这也将运行在6s(因为所有的方法是并行的)。 JUnitCore.runClasses(new ParallelComputer(false, true), classes);
您不应该从@Test调用JUnitCore.runClasses()。这会弄乱测试报告。请参阅:https://github.com/junit-team/junit4/issues/1102 并行运行测试的真正解决方案是扩展跑步者或套件 –