junit test run order code example

Example 1: junit testcase run in order

@TestMethodOrder(OrderAnnotation.class)
public class OrderAnnotationUnitTest {
    private static StringBuilder output = new StringBuilder("");
     
    @Test
    @Order(1)    
    public void firstTest() {
        output.append("a");
    }
     
    @Test
    @Order(2)    
    public void secondTest() {
        output.append("b");
    }
  
    @Test
    @Order(3)    
    public void thirdTest() {
        output.append("c");
    }
  
    @AfterAll
    public static void assertOutput() {
        assertEquals(output.toString(), "abc");
    }
}

Example 2: junit order

By adding @TestMethodOrder annotation
on top of class and 
than @Order tag on each test
with giving them number 

// these are all available option for ordering your tests
//@TestMethodOrder(OrderAnnotation.class)
//@TestMethodOrder(Random.class) //randomly run
//@TestMethodOrder(MethodName.class) // default options

For Example :

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

    @Order(3)
    @DisplayName("3. Test A method")
    @Test
    public void testA(){
        System.out.println("running test A");
    }
    @Order(1)
    @DisplayName("1. Test C method")
    @Test
    public void testC(){
        System.out.println("running test C");
    }
    @Order(4)
    @DisplayName("4. Test D method")
    @Test
    public void testD(){
        System.out.println("running test D");
    }
    @Order(2)
    @DisplayName("2. Test B method")
    @Test
    public void testB(){
        System.out.println("running test B");
    }
    
    
    In this case it will print 
    1. Test C
    2. Test B
    3. Test A
    4. Test D

Tags:

Java Example