How to run test methods in specific order in JUnit4?

后端 未结 18 2111
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 04:35

I want to execute test methods which are annotated by @Test in specific order.

For example:

public class MyTest {
    @Test public void          


        
18条回答
  •  刺人心
    刺人心 (楼主)
    2020-11-22 05:00

    JUnit 5 update (and my opinion)

    I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?

    By default, unit testing libraries don't try to execute tests in the order that occurs in the source file.
    JUnit 5 as JUnit 4 work in that way. Why ? Because if the order matters it means that some tests are coupled between them and that is undesirable for unit tests.
    So the @Nested feature introduced by JUnit 5 follows the same default approach.

    But for integration tests, the order of the test method may matter since a test method may change the state of the application in a way expected by another test method. For example when you write an integration test for a e-shop checkout processing, the first test method to be executed is registering a client, the second is adding items in the basket and the last one is doing the checkout. If the test runner doesn't respect that order, the test scenario is flawed and will fail.
    So in JUnit 5 (from the 5.4 version) you have all the same the possibility to set the execution order by annotating the test class with @TestMethodOrder(OrderAnnotation.class) and by specifying the order with @Order(numericOrderValue) for the methods which the order matters.

    For example :

    @TestMethodOrder(OrderAnnotation.class) 
    class FooTest {
    
        @Order(3)
        @Test
        void checkoutOrder() {
            System.out.println("checkoutOrder");
        }
    
        @Order(2)
        @Test
        void addItemsInBasket() {
            System.out.println("addItemsInBasket");
        }
    
        @Order(1)
        @Test
        void createUserAndLogin() {
            System.out.println("createUserAndLogin");
        }
    }
    

    Output :

    createUserAndLogin

    addItemsInBasket

    checkoutOrder

    By the way, specifying @TestMethodOrder(OrderAnnotation.class) looks like not needed (at least in the 5.4.0 version I tested).

    Side note
    About the question : is JUnit 5 the best choice to write integration tests ? I don't think that it should be the first tool to consider (Cucumber and co may often bring more specific value and features for integration tests) but in some integration test cases, the JUnit framework is enough. So that is a good news that the feature exists.

提交回复
热议问题