junit实现多个跑步者

vpr*_*han 7 java junit annotations suite junit-runner

我一直试图通过创建一个扩展跑步者的suiterunner来创建一个个性化的测试套件.在带有注释的测试套件中,@RunWith(suiterunner.class)我指的是需要执行的测试类.

在测试类中,我需要重复一个特定的测试,为此我正在使用这里提到的解决方案:http://codehowtos.blogspot.com/2011/04/run-junit-test-repeatedly.html.但是因为我创建了一个触发测试类的suiterunner并且在我正在实现的测试类中@RunWith(ExtendedRunner.class),所以抛出了初始化错误.

我需要帮助来管理这两个跑步者,还有什么方法可以将两个跑步者组合起来进行特定测试吗?有没有其他方法可以解决这个问题或任何更简单的方法来继续?

Nit*_*thi 2

如果您使用的是最新的 JUnit,您可能会使用 @Rules 来更清晰地解决您的问题。这是一个示例;

想象这是您的应用程序;

package org.zero.samples.junit;

/**
 * Hello world!
 * 
 */
public class App {
  public static void main(String[] args) {
    System.out.println(new App().getMessage());
  }

  String getMessage() {
    return "Hello, world!";
  }
}
Run Code Online (Sandbox Code Playgroud)

这是你的测试课;

package org.zero.samples.junit;

import static org.junit.Assert.*;

import org.junit.Rule;
import org.junit.Test;

/**
 * Unit test for simple App.
 */
public class AppTest {

  @Rule
  public RepeatRule repeatRule = new RepeatRule(3); // Note Rule

  @Test
  public void testMessage() {
    assertEquals("Hello, world!", new App().getMessage());
  }
}
Run Code Online (Sandbox Code Playgroud)

创建一个规则类,例如;

package org.zero.samples.junit;

import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;

public class RepeatRule implements TestRule {

  private int repeatFor;

  public RepeatRule(int repeatFor) {
    this.repeatFor = repeatFor;
  }

  public Statement apply(final Statement base, Description description) {
    return new Statement() {

      @Override
      public void evaluate() throws Throwable {
        for (int i = 0; i < repeatFor; i++) {
          base.evaluate();
        }
      }
    };
  }

}
Run Code Online (Sandbox Code Playgroud)

像往常一样执行您的测试用例,只是这次您的测试用例将重复给定的次数。您可能会发现有趣的用例,其中 @Rule 可能确实很方便。尝试创建复合规则,在你身边玩肯定会被粘住..

希望有帮助。