Skip to content

Instantly share code, notes, and snippets.

@fmbenhassine
Created April 3, 2018 09:35
Show Gist options
  • Save fmbenhassine/dc7711ea9a0d740a176b135e7f8e05b4 to your computer and use it in GitHub Desktop.
Save fmbenhassine/dc7711ea9a0d740a176b135e7f8e05b4 to your computer and use it in GitHub Desktop.
JUnit rule to repeat a test. Useful when testing multi-threaded behaviour which might succeed in one attempt but fail in another one.
public class RepeatTest implements TestRule {
private int count;
public RepeatTest(int count) {
if (count < 2 ) {
throw new IllegalArgumentException("Count must be >= 2");
}
this.count = count;
}
@Override
public Statement apply(Statement base, Description description) {
for (int i = 1; i <= count; i++) {
try {
base.evaluate();
} catch (Throwable throwable) {
throw new RuntimeException(throwable);
}
}
return base;
}
}
@fmbenhassine
Copy link
Author

How to use it:

public class MultiThreadedTests {

	@Rule
	public RepeatTest repeatTest = new RepeatTest(1000);

        // each test method will be executed 1000 times
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment