我正在使用 JUnit 进行广泛的测试,有时——在调试我的代码时——我希望(临时)只运行一个@Test
我的@RunWith(Arquillian.class)
测试类。目前我正在向@Ignore
所有其他测试添加 a 并想知道是否@IgnoreOther
存在类似的东西。
是否有更好的解决方案来忽略所有其他测试?
我正在使用 JUnit 进行广泛的测试,有时——在调试我的代码时——我希望(临时)只运行一个@Test
我的@RunWith(Arquillian.class)
测试类。目前我正在向@Ignore
所有其他测试添加 a 并想知道是否@IgnoreOther
存在类似的东西。
是否有更好的解决方案来忽略所有其他测试?
只是我的两分钱。您可以尝试按照@srkavin 的建议使用Junit 规则。
这是一个例子。
package org.foo.bar;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
public class SingleTestRule implements MethodRule {
private String applyMethod;
public SingleTestRule(String applyMethod) {
this.applyMethod = applyMethod;
}
@Override
public Statement apply(final Statement statement, final FrameworkMethod method, final Object target) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (applyMethod.equals(method.getName())) {
statement.evaluate();
}
}
};
}
}
package org.foo.bar;
import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
public class IgnoreAllTest {
@Rule
public SingleTestRule test = new SingleTestRule("test1");
@Test
public void test1() throws Exception {
System.out.println("test1");
}
@Test
public void test2() throws Exception {
Assert.fail("test2");
}
@Test
public void test3() throws Exception {
Assert.fail("test3");
}
}
最简单的方法是全部替换@Test
为//###$$$@Test
. 然后当你的调试完成后替换//###$$$@Test
为@Test
.
此外,IDE 通常只允许运行一项测试。例如,在 Eclipse 中,您可以从大纲视图中执行此操作。
测试规则(JUnit 4.7+)会有所帮助。例如,您可以编写一个规则,忽略所有 @Test 方法,但具有特定名称的方法除外。
srkavin(和mijer )的答案是正确的,但是从 JUnit 4.9 开始不推荐使用该代码。接口和方法签名已更改。我想为对这个问题感兴趣的其他人提供这个。
public class IgnoreOtherRule implements TestRule
{
private String applyMethod;
public IgnoreOtherRule(String applyMethod){
this.applyMethod = applyMethod;
}
@Override
public Statement apply(final Statement statement, final Description description)
{
return new Statement()
{
@Override
public void evaluate() throws Throwable {
if (applyMethod.equals(description.getMethodName())) {
statement.evaluate();
}
}
};
}
}