JUnit 5 Test Execution Order - Method Name, @Order, Random

How test execution order works: method-name order, @Order, and random execution

Test Execution Order

By default, JUnit 5 intentionally uses an algorithm whose order is not obvious. It is not truly random, but it should not be relied on. Original unit tests should not depend on execution order.

For integration tests or functional tests, however, execution order can matter. JUnit provides mechanisms to control test order for those cases.

Default Order

Without ordering annotations, tests may run in an order that differs from the method declaration order.

Method Name Order

Specify @TestMethodOrder(MethodOrderer.MethodName.class) on the test class to execute test methods in method-name order. MethodOrderer controls execution order, and MethodName sorts by comparing method names with java.util.Comparator.

Order with @Order

Using @TestMethodOrder(MethodOrderer.OrderAnnotation.class) lets you specify order with @Order. Methods without @Order are assigned Integer.MAX_VALUE by default.

Random Order

Using @TestMethodOrder(MethodOrderer.Random.class) executes methods in random order. This is useful for finding hidden dependencies between tests.