【问题标题】:How to order execution of controller test classes in Junit5 / spring boot?如何在 Junit5 / spring boot 中命令执行控制器测试类?
【发布时间】:2021-05-08 06:43:54
【问题描述】:

在我的实体中,我有双向的一对多关系,我想用 mock.mvc 编写集成测试。但是,在添加父级之前,我无法添加子级。出于这个原因,我想订购我的测试,例如首先运行 AirportControllerTest,其次是 RouteControllerTest,最后是 FlightController。

有没有可能,或者如何处理这种情况?

【问题讨论】:

    标签: java spring-boot hibernate jpa junit


    【解决方案1】:

    对于这个特定的问题,分层顺序比顺序顺序更好。

    如果您使用的是 JUnit 5,则可以使用 @Nested 测试。 https://junit.org/junit5/docs/current/user-guide/#writing-tests-nested

    以先运行父测试类的方式嵌套您的测试类,并且嵌套的测试可以使用父类创建的测试对象。

    这是一个高级示例:

    class AirportControllerTest{
    
        @Test
        void testAirportController() {
           //Add parent here
        }
    
        @Nested
        class RouteControllerTest {
          
            @Test
            void testRouteController() {
               //Use test objects from parent here
            }
            @Nested
            class FlightControllerTest{
          
               @Test
               void testFlightController() {
                  //Use test objects from AirportControllerTest & RouteControllerTest 
                }
        }
    }
    

    如果您使用的是 JUnit 4,您可以将您的测试类包含在测试套件中。这个答案很适合 - https://stackoverflow.com/a/42600619/6352160

    相关性较低:用于配置测试类中的测试方法顺序。

    如果您使用的是 JUnit5,请在您的 Test 类中指定 @TestMethodOrder 并在方法上使用 @Order 注释来指定它们的执行顺序。参考 - https://junit.org/junit5/docs/current/api/org.junit.jupiter.api/org/junit/jupiter/api/TestMethodOrder.html

    如果使用 JUnit4,这个问题有几种可能的解决方案 - How to run test methods in specific order in JUnit4?

    【讨论】:

    • 如果我没记错的话它会在一个类中订购测试方法,我想做的是订购测试类
    • @YektaAnılAksoy 我刚刚意识到我读错了这个问题。我的第一个答案是订购测试方法。我编辑了答案。
    猜你喜欢
    • 2021-02-08
    • 2019-05-17
    • 2021-12-22
    • 2018-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-07
    • 2018-01-02
    相关资源
    最近更新 更多