【问题标题】:How can I automatically skip certain JUnit tests based on a condition?如何根据条件自动跳过某些 JUnit 测试?
【发布时间】:2016-05-27 15:01:49
【问题描述】:

我想要一种简单的方法来为我的 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 真正跳过测试?

【问题讨论】:

标签: java junit junit-rule


【解决方案1】:

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();
            }
        };
    }
}

【讨论】:

  • 我的TestWatcher 子类中有其他starting()failed()finished() 方法,这些方法很容易在TestRule 中重新创建,还是值得创建一个单独的TestRule除了我现有的TestWatcher 子类之外,还有我的Assume 方法吗?
  • 查看 TestWatcher 的源代码:它只是一个简单的 TestRule 委托实现。您可以轻松地从 TestRule 重新实现您的 TestWatcher:github.com/junit-team/junit/blob/master/src/main/java/org/junit/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-13
相关资源
最近更新 更多