The @Order annotation helps control the order in which test methods run. This is useful when some tests depend on others or when you want a specific sequence.
0
0
@Order for execution order in JUnit
Introduction
You want to run a login test before tests that need a logged-in user.
You need to test a feature step-by-step in a certain order.
You want to ensure cleanup tests run after all other tests.
You want to organize tests logically for easier debugging.
You want to avoid random test execution order causing failures.
Syntax
JUnit
@Test
@Order(1)
void testMethod() {
// test code
}Use @Order with a number to set the execution priority.
Lower numbers run first. If no @Order is set, order is not guaranteed.
Examples
This test runs first because it has the lowest order number.
JUnit
@Test
@Order(1)
void firstTest() {
// runs first
}This test runs after the test with order 1.
JUnit
@Test
@Order(2)
void secondTest() {
// runs second
}This test has no order and may run anytime.
JUnit
@Test
void noOrderTest() {
// runs in any order
}Sample Program
This test class runs tests in the order: first(), second(), third() because of the @Order annotations.
The output shows the order of execution.
JUnit
import org.junit.jupiter.api.*; import org.junit.jupiter.api.MethodOrderer.OrderAnnotation; @TestMethodOrder(OrderAnnotation.class) public class OrderedTests { @Test @Order(2) void second() { System.out.println("Second test running"); Assertions.assertTrue(true); } @Test @Order(1) void first() { System.out.println("First test running"); Assertions.assertTrue(true); } @Test @Order(3) void third() { System.out.println("Third test running"); Assertions.assertTrue(true); } }
OutputSuccess
Important Notes
Remember to add @TestMethodOrder(OrderAnnotation.class) at the class level to enable ordering.
Ordering tests can hide dependencies; ideally, tests should be independent.
Summary
@Order sets the order of test execution by number.
Lower numbers run before higher numbers.
Use @TestMethodOrder(OrderAnnotation.class) on the class to activate ordering.