Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Simple JUnit rule to make tests retry
public class RetrierTest {
private static int count = 0;
@Rule public RetryRule rule = new RetryRule();
@Test
@Retry
public void failsFirst() throws Exception {
count++;
assertEquals(2, count);
}
}
@Retention(RetentionPolicy.RUNTIME)
public @interface Retry {}
public class RetryRule implements MethodRule {
@Override public Statement apply(final Statement base, final FrameworkMethod method, Object target) {
return new Statement() {
@Override public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable t) {
Retry retry = method.getAnnotation(Retry.class);
if (retry != null) {
base.evaluate();
} else {
throw t;
}
}
}
};
}
}

braghome commented Jun 5, 2015

what if their is a requirement to only retry till count of 3

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