Skip to content

Instantly share code, notes, and snippets.

@dfparker2002
Forked from mkempka/Manifold.java
Created June 20, 2013 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dfparker2002/5825402 to your computer and use it in GitHub Desktop.
Save dfparker2002/5825402 to your computer and use it in GitHub Desktop.
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