How to Run JUnit 5 Tests in a Specific Order

By default, JUnit runs tests in an unpredictable order. There are times when you want to run your tests in a specific order.

For example, imagine a scenario where you are testing a user management API. The scenarios would be in this specific order:

  • 1 - Test create user
  • 2 - Test update user
  • 3 - Test delete user

In order to update or delete a user, we need to first create the user.

In JUnit 5, we can use @TestMethodOrder and @Order annotations to run tests in order.

Running Tests in Order

Example:

import org.junit.jupiter.api.*;

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

    @Test
    @Order(1)
    public void testCreateUser() {
        // code to test user creation
    }

    @Test
    @Order(2)
    public void testUpdateUser() {
        // code to test user update
    }

    @Test
    @Order(2)
    public void testDeleteUser() {
        // code to test user deletion
    }
}

With the above annotations, the tests will run in the specified order.