Introduction
Good unit tests should not rely on the order that they are run. But sometimes, there a test cases that you need to run in a specific order, for example, integration tests.
JUnit5 Built-in orderers
Junit offers five built-in ways to control the order in which the tests are executed:
OrderAnnotation: We can use annotations to execute tests in a specific order.DisplayName: Sorts test by their display name.MethodName: Orders the test by their method name.Alphanumeric: This class is deprecated and will be removed with JUnit6. It works the same as MethodName.Random: This causes your tests to be run in a different order each time.
Using the @Order annotation
With @TestMethodOrder(OrderAnnotation.class) above your test class, you can use the @Order annotation to specify
the order the tests are executed. The following example will first run the test with @Order(1), followed by the test annotated with @Order(2).
| |
Run tests in order of their method name
When you annotate your test class with @TestMethodOrder(MethodName.class), the test will be executed according to its method name and parameter list.
In the following example the execution order would be: a(), a(int i), b().
You could also use @TestMethodOrder(Alphanumeric.class), but I would not recommend it as it will be removed with JUnit6.
| |
Run test in order of their display name
You can also choose to execute tests in the order of their display name, as in the following example.
| |
Ordering tests in JUnit4
Setting the execution order of tests in JUnit4 is different from JUnit5. The following example orders the test execution by method name.
| |
Conclusion
This article looked at different ways to run your tests in a specific order using JUnit. If you want to know more about the execution order or JUnit5, please see the official docs.
Further reading
More about testing in Java:
Level Up Your Team's Java Testing: JUnit 5, Mockito & Testcontainers
Slow, flaky, or brittle test suites kill developer velocity. In my 1-day Modern Testing in Java Workshop, your team learns how to design fast, maintainable unit and microservice integration tests using advanced JUnit 5, Mockito, and Testcontainers on your real codebase.
Want More Deep-Dive JVM Benchmarks & Project Panama Research?
Follow my weekly engineering posts on LinkedIn, explore the full JMH benchmark suites and pure-Java Linux io_uring / FUSE projects on GitHub, or download my conference talk slides: