Advertise with us

Our eBooks

How to control JUnit Tests order

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;

class OrderedTestsDemo {

    void test1() {
        // This test first

    void test2() {
        // Then this test

    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 {

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

    void testWithDisplayNameAndEmoji() {

© 2021 All Rights Reserved.

Please publish modules in offcanvas position.