Skip to content

Instantly share code, notes, and snippets.

@mkempka
Created May 22, 2013 11:59
Show Gist options
  • Save mkempka/5627026 to your computer and use it in GitHub Desktop.
Save mkempka/5627026 to your computer and use it in GitHub Desktop.
A rule runs a test case many times in parallel. Can be used for load tests. If more than one of the parallel executions fails, only the first fail is reported. Example: To run each test method in the class 5 times, add @rule public Manifold runParallel = new Manifold(5); to the class
import java.util.concurrent.CountDownLatch;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
/**
* A rule runs each test case many times in parallel. Can be used for load tests. If more than one
* of the parallel executions fails, only the first fail is reported. Example: To run each test
* method in the class 5 times, add <code> @Rule
public Manifold runParallel = new Manifold(5);</code> to the
* class
*
* @author Matthias Kempka
*/
public class Manifold implements TestRule {
private final int threadCount;
public class RunOften extends Statement {
private final Statement base;
public RunOften(final Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
final CountDownLatch latch = new CountDownLatch(threadCount);
final Throwable[] exceptions = new Throwable[threadCount];
for (int i = 0; i < threadCount; i++) {
Runnable sample = new Runnable() {
public void run() {
try {
base.evaluate();
} catch (Throwable e) {
exceptions[0] = e;
} finally {
latch.countDown();
}
}
};
new Thread(sample).start();
}
// wait
latch.await();
for (int i = 0; i < threadCount; i++) {
if (exceptions[i] != null) {
throw exceptions[i];
}
}
}
}
public Manifold(final int threadCount) {
this.threadCount = threadCount;
}
public int getThreadCount() {
return threadCount;
}
public Statement apply(final Statement base, final Description description) {
return new RunOften(base);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment