Sunday, April 30, 2017
It was easier than I thought
It was easier than I thought
I wanted a way to distribute JUnit tests among multiple threads. I couldnt believe how easy it turned out to be.
public class ParallelTestSuite extends TestSuite {
private final int numWorkers;
public ParallelTestSuite(int numWorkers) {
this.numWorkers = numWorkers;
}
@Override public void run(TestResult result) {
final ExecutorService executor
= Executors.newFixedThreadPool(numWorkers);
TestResult newResult = new ForwardingTestResult(result) {
@Override protected void run(final TestCase test) {
executor.execute(new Runnable() {
public void run() {
superRun(test);
}
});
}
private void superRun(TestCase test) {
super.run(test);
}
};
super.run(newResult);
executor.shutdown();
try {
executor.awaitTermination(3600, TimeUnit.SECONDS);
} catch (InterruptedException e) {
}
}
}
ForwardingTestResult is just what it sounds like; a TestResult that forwards all its method calls to another TestResult.
I found it interesting that I couldnt really figure out how to avoid needing that one-line "superRun()" method. What else could I do?
Anyone out there who understands JUnit and java.util.concurrent have any helpful criticism for how to make this better?
Available link for download