简体   繁体   English

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

[英]Interrupt test class at the first test failure

I have a JUnit 5 test consisting of multiple steps executing in order.我有一个 JUnit 5 测试,包括按顺序执行的多个步骤。 The steps are defined in separate methods.这些步骤在不同的方法中定义。

I want the tests to stop executing at first failure in the fixture/class.我希望测试在夹具/类中的第一次失败时停止执行。

This is behaviour which can be achieved in Spock by using @Stepwise annotation.这是可以在 Spock 中通过使用@Stepwise注释来实现的行为。 I don't see how this can be done in JUnit 5.我看不出如何在 JUnit 5 中做到这一点。

Edit: added sample test编辑:添加了示例测试

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

Gives the following result:给出以下结果:

1596054675044 test 1 - ok
1596054675075 test 2

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

1596054675111 test 3 - ok
1596054675115 test 4 - ok

You can achieve that using an assert in each step, because JUnit stops it's execution process when an assert failed.您可以在每个步骤中使用断言来实现这一点,因为 JUnit 在断言失败时会停止其执行过程。

If you want JUnit engine to stop running other @Test methods as soon as one of those fails, then it's not possible .如果您希望 JUnit 引擎在其中一个失败时立即停止运行其他@Test方法,那么这是不可能的

JUnit Engine takes your fixture (Test class), and instantiates its new object per each @Test method, and note(,), that execution of those @Test methods are unpredictable to you. JUnit 引擎获取您的夹具(测试类),并为每个@Test 方法实例化其的 object,并注意(,),这些@Test方法的执行对您来说是不可预测的。 So, even if one @Test fails, JUnit needs to test other @Test methods and it will do so.因此,即使一个@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?从这个角度考虑:如果 JUnit 在第一次故障后立即停止,那么如何测试您的软件的其他哪些单元发生故障? say you have 1000 @Test methods, and 2nd fails, aren't you interested to test other 998 units?假设您有 1000 个 @Test 方法,并且第二个失败了,您是否有兴趣测试其他 998 个单元?

It seems impossible to achieve this by adding JUnit5 annotation yet.似乎还不可能通过添加 JUnit5 注释来实现这一点。

However, all infrastructure is there to implement your own extension, similar to one in issue comment但是,所有基础设施都可以实现您自己的扩展,类似于问题评论中的一个

That works exactly as intended.这完全符合预期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM