JUnit tests are executed using a deterministic (but not obvious) criteria, however it's possible to define the exact order of Test execution. This tutorial shows how to do it.

Even if true unit tests should not rely on a precise order in which they are executed, sometimes it is needed to enforce a specific order for your tests.

To control the order in which test methods are executed, you can annotate your test class with @TestMethodOrder and specify which criteria you want to use for ordering tests, among the following options:

  • Alphanumeric: the order of test is chosen alphanumerically based on the method names
  • OrderAnnotation: the order of tests is specified with a number
  • Random: tests are executed using a random order

The following example demonstrates how to guarantee that test methods are executed in the order specified via the @Order annotation.

import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;

@TestMethodOrder(OrderAnnotation.class)
class OrderedTestsDemo {

    @Test
    @Order(1)
    void test1() {
        // This test first
    }

    @Test
    @Order(2)
    void test2() {
        // Then this test
    }

    @Test
    @Order(3)
    void test3() {
        Finally this test
    }

}

  You can specify a custom display name for your tests using the @DisplayName annotation which accepts spaces, special characters, and even emojis. Here is an example:

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("This will display in the Test Report")
class ExampleDisplayName {

    @Test
    @DisplayName("Custom test name")
    void testWithDisplayName() {
    }

    @Test
    @DisplayName("😱")
    void testWithDisplayNameAndEmoji() {
    }

}
FREE WildFly Application Server - JBoss - Quarkus - Drools Tutorials