在第一次测试失败时中断测试 class

Interrupt test class at the first test failure

我有一个 JUnit 5 测试,其中包含按顺序执行的多个步骤。这些步骤在单独的方法中定义。

我希望测试在 fixture/class 中的第一次失败时停止执行。

这是可以在 Spock 中使用 @Stepwise 注释实现的行为。我不知道如何在 JUnit 5 中完成此操作。

编辑:添加了示例测试

@TestMethodOrder(Alphanumeric.class)
class MainTest {

    @Test void test1() {
        assertTrue(true);
        System.out.printf("%d test 1 - ok%n", System.currentTimeMillis());
    }

    @Test void test2() {
        assertTrue(false);
        System.out.printf("%d test 2 -nok%n", System.currentTimeMillis());
    }

    @Test void test3() {
        assertTrue(true);
        System.out.printf("%d test 3 - ok%n", System.currentTimeMillis());
    }

    @Test void test4() {
        assertTrue(true);
        System.out.printf("%d test 4 - ok%n", System.currentTimeMillis());
    }
}

给出以下结果:

1596054675044 test 1 - ok
1596054675075 test 2

org.opentest4j.AssertionFailedError: 
Expected :true
Actual   :false

1596054675111 test 3 - ok
1596054675115 test 4 - ok

您可以在每个步骤中使用断言来实现这一点,因为当断言失败时 JUnit 会停止其执行过程。

如果您希望 JUnit 引擎在其中一个失败时立即停止 运行 其他 @Test 方法,那么不可能.

JUnit 引擎获取您的夹具(测试 class),并根据 each @Test 方法实例化其 new 对象,并注意(!),那些 @Test 方法的执行对您来说是不可预测的。因此,即使一个 @Test 失败,JUnit 也需要测试其他 @Test 方法,它会这样做。

Think about it from this perspective: If JUnit were to stop right after first failure, then how would it be possible to test what other units of your software are failing? say you have 1000 @Test methods, and 2nd fails, aren't you interested to test other 998 units?

似乎还不可能通过添加 JUnit5 注释来实现。

但是,所有基础设施都可以实现您自己的扩展,类似于 issue comment

这完全符合预期。