Skip to content

Instantly share code, notes, and snippets.

@abyx
Created March 31, 2011 20:51
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save abyx/897229 to your computer and use it in GitHub Desktop.
Save abyx/897229 to your computer and use it in GitHub Desktop.
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;
}
}
}
};
}
}
@a-oleynik
Copy link

@tomdwp
public class RetryRule implements MethodRule {

private AtomicInteger retryCount;

public RetryRule() {
    this(3);
}

public RetryRule(int retries) {
    super();
    this.retryCount = new AtomicInteger(retries);
}

@Override
public Statement apply(final Statement base, final FrameworkMethod method, Object target) {
    return new Statement() {
        @Override
        public void evaluate() throws Throwable {
            Throwable caughtThrowable = null;

            while (retryCount.getAndDecrement() > 0) {
                try {
                    base.evaluate();
                    return;
                } catch (Throwable t) {
                    if (retryCount.get() > 0 &&
                            method.getAnnotation(Retry.class) != null) {
                        caughtThrowable = t;
                        System.err.println(
                                method.getName() +
                                        ": Failed, " +
                                        retryCount.toString() +
                                        "retries remain");
                    } else {
                        throw caughtThrowable;
                    }
                }
            }
        }
    };
}

}

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