JUnit 5: How to run the test cases in a specific order in JUnit?

Backend Pro

 In some cases, we might need to specify the order in which the test cases must be executed. for ex: you want to run the test suite in an order in which data is inserted into a table in first test case and then updates the data in second test case, and finally deletes the data in the third test case. 

In Junit5, this can be done by using two annotations

1.@TestMethodOrder(MethodOrderer.OrderAnnotation.class)

2. @Order 

Make sure these 2 annotations are used, if you just use @Order annotation, it doesn't work. 

Let's see the example in which we can run the test cases in specific order these annotations. 


import org.junit.jupiter.api.*;

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class SpecificOrderTest {

    @Test
    @Order(1)
    public void test1() {
        int a = 1;
        int b = 2;
        int c = a + b;
        Assertions.assertTrue(c == 3);
    }

    @Test
    @Order(3)
    public void test2() {
        int a = 2;
        int b = 1;
        int c = a - b;
        Assertions.assertTrue(c == 1);
    }

    @Test
    @Order(2)
    public void test3() {
        int a = 2;
        int b = 1;
        int c = a * b;
        Assertions.assertTrue(c == 2);
    }
}

Once we run this test class, we can see the test results as below. 


The execution of test cases are in the same order as mentioned with the @Order annotation. 
  1. test1() is executed first as it's order is 1.
  2. test3() is executed next as it's order is 2.
  3. test2() is executed at the last as it's order is 3. 

@Order annotation, orders the methods based on the priority. A lower value will have higher priority than a higher value. Which means a value 1 has higher priority than the value 2. Make sure you provide correct value to @Order annotation, so that test cases are executed in the expected order. 


Tags

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !