当 JUnit 5 外部测试用例失败时,不要启动嵌套测试用例

2024-04-22

我有以下测试类:

import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import static org.junit.jupiter.api.Assertions.assertTrue;

public class HierarchicalTest {

    @Test
    void checkOuter() {
        assertTrue(false);
    }

    @Nested
    @TestInstance(TestInstance.Lifecycle.PER_CLASS)
    class PrepBTest {

        @Test
        void checkInnerA() {}

        @Test
        void checkInnerB() {}
    }
}

我想要有这样的行为checkInnerA() and checkInnerB()时不会被执行checkOuter() fails.

另一方面checkInnerB()应该执行时checkInnerA()失败是因为它处于同一级别。

是否有一个简单的解决方案(例如使用 JUnit 5 扩展)来实现此行为? 在我看来,这通常是人们所希望的行为。


UPDATE:

从 JUnit Jupiter 5.4 开始,您可以开发一个扩展来实现TestWatcher and ExecutionConditionAPI 来实现此行为。

In the testFailed()方法从TestWatcher您需要跟踪出现故障的 API 测试类,并且需要将此信息存储在root ExtensionContext.Store.

In the evaluateExecutionCondition()方法从ExecutionCondition你需要判断当前类是否是一个API@Nested测试类(即内部类)并检查封闭的测试类是否失败。如果这是真的,你需要disable当前的@Nested测试类和其他enable it.

这些是一般准则。有关工作示例,请参阅SkipOnFailuresInEnclosureClassExtension https://github.com/sbrannen/junit5-demo/blob/master/src/main/java/extensions/SkipOnFailuresInEnclosingClassExtension.java我刚刚发布到我的junit5-demoGitHub 上的存储库。该示例更进一步,仅跳过@Nested测试类是否也带有注释@SkipOnFailuresInEnclosingClass. The 外部测试 https://github.com/sbrannen/junit5-demo/blob/master/src/test/java/working/OuterTests.java类显示了正在运行的注释和扩展。


不可以,从 JUnit Jupiter 5.3 开始,目前无法通过开箱即用的解决方案来实现这一目标。

您可能会编写一个自定义扩展来跟踪封闭测试类中测试的成功 - 例如,通过实现TestExecutionExceptionHandler。这需要存储在ExtensionContext.Store。然后扩展需要实现ExecutionCondition以编程方式disable嵌套测试类。

不幸的是,目前跟踪以前执行的测试的“成功”并不是很简单,但是随着新测试的引入,情况应该会有所改善TestWatcher目前计划包含在即将推出的 JUnit Jupiter 5.4 中的扩展 API:https://github.com/junit-team/junit5/issues/542 https://github.com/junit-team/junit5/issues/542

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

当 JUnit 5 外部测试用例失败时,不要启动嵌套测试用例 的相关文章

随机推荐