我想在多个类中同时运行每个用 @Test
注释的方法。对于某些情况,我想对此进行限制,并说每次只能运行 100 个。我希望带有 @BeforeClass
注释的方法在类中的任何测试运行之前运行一次,并且我希望 @AfterClass
注释在所有测试之后运行一次类(class)运行。我希望 System.out
、System.err
和 Exceptions 被适本地缓冲/捕获而不是写出,这样它们就不会交错,我可以阅读最终输出并了解发生了什么。
这存在吗?我有大量独立的测试用例,我的应用程序(我相信)是线程安全的。这些测试都没有 JVM 之外的依赖项,鉴于我的硬件,我想尽快完成它们。
如果不存在,是否有具体原因?全世界的 junit 用户因为这不容易而浪费了多少时间?我可以将它构建到 Junit 中吗?在我看来,这应该像一个标志一样简单,而且它“正常工作”。
您可以使用 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 秒内运行,因为所有方法和类都是并行运行的。
这将在 6 秒内运行(因为所有类都是并行的)。
JUnitCore.runClasses(new ParallelComputer(true, false), classes);
这也将在 6 秒内运行(因为所有方法都是并行的)。
JUnitCore.runClasses(new ParallelComputer(false, true), classes);