I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE COURSE

1. Overview

By default, JUnit runs tests using a deterministic, but unpredictable order (MethodSorters.DEFAULT).

In most cases, that behavior is perfectly fine and acceptable; but there’re cases when we need to enforce a specific ordering.

2. Using MethodSorters.DEFAULT

This default strategy compares test methods using their hashcodes. In case of a hash collision, the lexicographical order is used:

@FixMethodOrder(MethodSorters.DEFAULT)
public class DefaultOrderOfExecutionTest {
    private static StringBuilder output = new StringBuilder("");

    @Test
    public void secondTest() {
        output.append("b");
    }

    @Test
    public void thirdTest() {
        output.append("c");
    }

    @Test
    public void firstTest() {
        output.append("a");
    }

    @AfterClass
    public static void assertOutput() {
        assertEquals(output.toString(), "cab");
    }
}

When we execute the tests in the class above, we will see that they all pass, including assertOutput().

3. Using MethodSorters.JVM

Another ordering strategy is MethodSorters.JVMthis strategy utilizes the natural JVM ordering – which can be different for each run:

@FixMethodOrder(MethodSorters.JVM)
public class JVMOrderOfExecutionTest {
    // same as above
}

Each time we execute the tests in this class, we get a different result.

4. Using MethodSorters.NAME_ASCENDING

Finally, this strategy can be used for running test in their lexicographic order:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class NameAscendingOrderOfExecutionTest {
    // same as above
    
    @AfterClass
    public static void assertOutput() {
        assertEquals(output.toString(), "abc");
    }
}

Similarly, when we execute the tests in this class, we see that they all pass, including assertOutput(), which confirms the execution order that we set with the annotation.

5. Conclusion

In this quick tutorial, we went through the ways of setting the execution order available in JUnit.

And, as always, the examples used in this article can be found over on GitHub.

I just announced the new Spring 5 modules in REST With Spring:

>> CHECK OUT THE LESSONS

Leave a Reply

2 Comments on "The Order of Tests in JUnit"

Notify of
avatar
Sort by:   newest | oldest | most voted
Christian Stein
Guest
Sam Brannen
Guest

The content of this article is related to JUnit 4, *not* JUnit 5.