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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
