Testing / JUnit6 Interview Questions
How does test ordering work in JUnit 6 with @TestMethodOrder?
By default JUnit 6 uses a deterministic but non-obvious method order. @TestMethodOrder lets you explicitly control execution order. In JUnit 6, this annotation is recursively inherited by @Nested classes.
| Orderer | Behaviour |
|---|---|
| MethodOrderer.OrderAnnotation | Methods run in @Order(n) value order (ascending) |
| MethodOrderer.DisplayName | Methods run in display name alphanumeric order |
| MethodOrderer.MethodName | Methods run in method name alphanumeric order |
| MethodOrderer.Random | Methods run in random order (with optional seed for reproducibility) |
| MethodOrderer.Alphanumeric | Removed in JUnit 6: replaced by DisplayName or MethodName |
import org.junit.jupiter.api.*; @TestMethodOrder(MethodOrderer.OrderAnnotation.class) class OrderedTest { @Test @Order(1) void firstStep() { System.out.println("1"); } @Test @Order(2) void secondStep() { System.out.println("2"); } @Test @Order(3) void thirdStep() { System.out.println("3"); } // JUnit 6: @TestMethodOrder is inherited by @Nested classes @Nested class NestedSteps { // No @TestMethodOrder needed -- inherited from outer class @Test @Order(1) void nestedFirst() { System.out.println("N1"); } @Test @Order(2) void nestedSecond() { System.out.println("N2"); } } } // Random order with seed (reproducible): @TestMethodOrder(MethodOrderer.Random.class) class RandomOrderTest { // Set seed for reproducible random: // junit.jupiter.execution.order.random.seed=42 // in junit-platform.properties }
Breaking change: MethodOrderer.Alphanumeric was deprecated in JUnit 5 and removed in JUnit 6. Use MethodOrderer.DisplayName or MethodOrderer.MethodName instead.
More Related questions...