JUnit 4 Test Execution Order Example

1. Overview

In this guide, we will learn how to execute tests in order. By default, JUnit executes tests in any order.
The source code for this example is available on GitHub.

2. Test execution order

To change the test execution order simply annotate your test class using @FixMethodOrder and specify one of the available MethodSorters:
@FixMethodOrder(MethodSorters.JVM): Leaves the test methods in the order returned by the JVM. This order may vary from run to run.

@FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

3. Example

package com.developersguide.junit;

import org.junit.FixMethodOrder;

import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {

    @Test
    public void testA() {
        System.out.println("first");
    }
    @Test
    public void testB() {
        System.out.println("second");
    }
    @Test
    public void testC() {
        System.out.println("third");
    }
    
    @Test
    public void testE() {
        System.out.println("fifth");
    }
    
    @Test
    public void testD() {
        System.out.println("fourth");
    }
}
Above code will execute the test methods in the order of their names, sorted in ascending order.

Output:


4. Conclusion

In this guide, we learned how to execute tests in order. By default, JUnit executes tests in any order. The source code for this example is available on GitHub


Comments