如何根据条件自动跳过某些JUnit测试?

时间:2016-02-16 11:01:56

标签: java junit junit-rule

我想用一种简单的方法为我的JUnit测试分配优先级值,这样我就可以说'只运行优先级1测试','运行优先级1,2和3测试'等等。我知道我可以在每个测试开始时包括Assume.assumeTrue("Test skipped for priority " + priority, priority <= 2);之类的行(其中priority是我想要运行的最高值优先级测试,2是此特定测试的优先级值),但是复制 - 在每次测试开始时添加一条线似乎不是一个很好的解决方案。

我尝试使用一个简单的注释编写解决方案,该注释由我正在使用的JUnit规则检测:

public class Tests {
    @Rule
    public TestRules rules = new TestRules();
    @Test
    @Priority(2)
    public void test1() {
        // perform test
    }
}

public class TestRules extends TestWatcher {
    private int priority = 1; // this value is manually changed to set the priority of tests to run
    @Override
    protected void starting(Description desc) {
        Priority testCasePriority = desc.getAnnotation(Priority.class);
        Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority);
    }
}

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Priority {
    public int value() default 0;
}

虽然这似乎有效(在Eclipse JUnit视图中显示正确的测试被跳过),但测试仍在执行,即test1()中的任何代码仍在运行。

有没有人知道如何让我的规则中的Assume真正跳过测试?

1 个答案:

答案 0 :(得分:3)

忽略TestWatcher.starting抛出的异常,并在测试结束时重新抛出。

您应该实施TestRule而不是TestWatcher

public class TestRules implements TestRule {
    private int priority = 1; // this value is manually changed to set the priority of tests to run

     public Statement apply(final Statement base, final Description description) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                Priority testCasePriority = desc.getAnnotation(Priority.class);
                Assume.assumeTrue("Test skipped for priotity " + priority, testCasePriority == null || testCasePriority.value() <= priority);

                base.evaluate();
            }
        };
    }
}