← Back to libraryQuestion 271 of 468
🔬TestNG & JUnitIntermediate

Test Priority and Execution Order

📌 Definition:

By default TestNG runs @Test methods in alphabetical order, not definition order. priority controls order (lower runs first); JUnit 5 is unordered by default but supports @Order with a MethodOrderer.

📖 Detailed Explanation:

TestNG @Test(priority = 1) sets execution order (default priority is 0; equal priorities fall back to alphabetical). You can also order by dependencies. JUnit 5 does NOT guarantee order (encouraging independent tests) but allows @TestMethodOrder(OrderAnnotation.class) + @Order(n) when order matters. Best practice in BOTH is to make tests INDEPENDENT so order doesn't matter — relying on execution order is fragile and breaks under parallelism. Priorities/order are for the rare cases where a genuine sequence is required (and even then, shared setup is usually better).

🔑 Key Points:
  • TestNG default order is ALPHABETICAL, not source order
  • priority (lower first) sets TestNG order; JUnit5 uses @Order + MethodOrderer
  • Prefer INDEPENDENT tests — order reliance is fragile
  • Order breaks under parallel execution
🌍 Real-World Example:

A tester assumes tests run top-to-bottom and a later test depends on an earlier one; under TestNG they run alphabetically and it fails — fixed by making each test set up its own state (independent).

🎯 Scenario-Based Interview Question:

A TestNG class runs its tests in an unexpected order, breaking a test that assumed the previous one ran first. What's happening and the right fix?