1By adding @TestMethodOrder annotation
2on top of class and
3than @Order tag on each test
4with giving them number
5
6// these are all available option for ordering your tests
7//@TestMethodOrder(OrderAnnotation.class)
8//@TestMethodOrder(Random.class)
9//@TestMethodOrder(MethodName.class) // default options
10
11For Example :
12
13@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
14public class TestOrderingInJunit5 {
15
16 @Order(3)
17 @DisplayName("3. Test A method")
18 @Test
19 public void testA(){
20 System.out.println("running test A");
21 }
22 @Order(1)
23 @DisplayName("1. Test C method")
24 @Test
25 public void testC(){
26 System.out.println("running test C");
27 }
28 @Order(4)
29 @DisplayName("4. Test D method")
30 @Test
31 public void testD(){
32 System.out.println("running test D");
33 }
34 @Order(2)
35 @DisplayName("2. Test B method")
36 @Test
37 public void testB(){
38 System.out.println("running test B");
39 }
40
41
42 In this case it will print
43 1. Test C
44 2. Test B
45 3. Test A
46 4. Test D
1@TestMethodOrder(OrderAnnotation.class)
2public class OrderAnnotationUnitTest {
3 private static StringBuilder output = new StringBuilder("");
4
5 @Test
6 @Order(1)
7 public void firstTest() {
8 output.append("a");
9 }
10
11 @Test
12 @Order(2)
13 public void secondTest() {
14 output.append("b");
15 }
16
17 @Test
18 @Order(3)
19 public void thirdTest() {
20 output.append("c");
21 }
22
23 @AfterAll
24 public static void assertOutput() {
25 assertEquals(output.toString(), "abc");
26 }
27}
28