我一直在尝试通过创建一个扩展 runner 的 suiterunner 来创建一个个性化的测试套件。在用 @RunWith(suiterunner.class)
注释的测试套件中,我指的是需要执行的测试类。
在测试类中我需要重复一个特定的测试,为此我使用这里提到的解决方案:http://codehowtos.blogspot.com/2011/04/run-junit-test-repeatedly.html .但是由于我已经创建了一个触发测试类的 suiterunner,并且在该测试类中我正在实现 @RunWith(ExtendedRunner.class)
,因此会引发初始化错误。
我需要帮助来管理这 2 个运行者,还有什么方法可以将 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!";
}
}
这是你的测试类;
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());
}
}
创建一个规则类;
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();
}
}
};
}
}
像往常一样执行您的测试用例,只是这次您的测试用例将重复给定的次数。您可能会发现有趣的用例,其中 @Rule 可能真的很方便。尝试创建复合规则,在你周围玩耍肯定会被粘住..
希望对您有所帮助。
关于java - 多个运行者的junit实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7846314/