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

Dav*_*ave 6 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;
}
Run Code Online (Sandbox Code Playgroud)

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

有没有人知道如何让Assume我的规则实际上跳过测试?

Jér*_*e B 5

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

您应该实施 aTestRule而不是 a 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();
            }
        };
    }
}
Run Code Online (Sandbox Code Playgroud)