7

我想要一种简单的方法来为我的 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在我的规则中实际跳过测试?

4

1 回答 1

5

a 抛出的异常被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();
            }
        };
    }
}
于 2016-02-16T11:07:42.220 回答