mherod
3/31/2011 - 8:51 PM

Simple JUnit rule to make tests retry

Simple JUnit rule to make tests 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;
          }
        }
      }
    };
  }
}
@Retention(RetentionPolicy.RUNTIME)
public @interface 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);
  }
}