1

我做了以下自定义BlockJUnit4ClassRunner

  public class RepeatEachTest extends BlockJUnit4ClassRunner {

  private int repeats;

  public RepeatEachTest(Class<?> klass) throws InitializationError {
    super(klass);
    Repeat r = klass.getAnnotation(Repeat.class);
    if (r == null) {
        throw new InitializationError("A @Repeat annonation must also be suplied to class, for example @Repeat(5) to repeat 5 times");
    }
    repeats = r.value();
  }

  @Override
  protected void runChild(FrameworkMethod method, RunNotifier notifier) {
    for (int i = 0; i < repeats; i++) {
        super.runChild(method, notifier);
    }
  }

  @Override
  public int testCount() {
    return repeats * super.testCount();
  }
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Repeat {  
 int value();
}

执行每个测试@Repeat.value()的次数。试运行

@RunWith(RepeatEachTest.class)
@Repeat(2)
public class RepeatEachTestTest {

  @Test
  public void first() {
    System.out.println("ran first");
  }

  @Test
  public void second() {
    System.out.println("ran second");
  }
}

好像

ran first
ran first
ran second
ran second

但现在我想实现第二个BlockJUnit4ClassRunner运行整个测试类 @Repeat.value()的次数。从该设置运行看起来像

ran first
ran second
ran first
ran second

有什么想法吗?

4

1 回答 1

1

这取决于你想要什么。如果您希望多次调用@BeforeClassand方法和类规则,您可以覆盖:@AfterClassclassBlock()

protected Statement classBlock(final RunNotifier notifier) {
  return new Statement() {
    @Override
    public void evaluate() throws Throwable {
      for (int i = 0; i < repeats; i++) {
        super.classBlock(notifier).evaluate();
      }
    }
  };
}

如果您希望一次调用@BeforeClassand方法和类规则,请覆盖(代码类似)。@AfterClasschildrenInvoker()

但是请注意,其中任何一个都会导致侦听器多次收到测试已经开始和完成的通知。在这种情况下,某些侦听器的行为可能不正确。

于 2013-03-06T08:03:29.090 回答