Using @FixMethodOrder
[wp_ad_camp_5]
To execute tests in a order in JUnit 4, annotate the class with @FixedMethodOrder passing one of enum MethodSorters items as parameter. Either one of the following can be used are parameter to @FixMethodOrder.
- MethodSorters.NAME_ASCENDING: This sorts the test methods by the method name in the lexicographic order.
- MethodSorters.DEFAULT: Does not guarantee the execution order.
- MethodSorters.JVM: The sort order is determined by the JVM.
JUnit Tests Not using @FixMethodOrder
Without using @FixMethodOrder, the order of execution is not guaranteed.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | package com.turreta.junit4.fixmethodorder; import org.junit.Before; import org.junit.Test; /** * * @author Turreta.com * * Test the order of execution of test methods. Order of execution is not guaranteed here. * */ public class ExecutionOrderTest{ @Before public void setUp() throws Exception { } @Test public void create() { System.out.println("create"); } @Test public void delete() { System.out.println("delete"); } @Test public void mark_deleted() { System.out.println("mark_deleted"); } @Test public void mark_modified() { System.out.println("mark_modified"); } @Test public void update() { System.out.println("update"); } @Test public void reset() { System.out.println("reset"); } } |
The test execution order (varies in every execution) is as follows.
[wp_ad_camp_4]
JUnit Tests using @FixMethodOrder
With a similar class annotated with @FixMethodOrder, we’d expect the execution order is by method name in ascending lexicographic order.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | package com.turreta.junit4.fixmethodorder; import org.junit.Before; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; /** * * @author Turreta.com * * Test execution order of test methods. Execution order is as follow: * 1. create * 2. delete * 3. mark_deleted * 4. mark_modified * 5. reset * 6. update * */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class FixMethodOrderTest{ @Before public void setUp() throws Exception { } @Test public void create() { System.out.println("create"); } @Test public void delete() { System.out.println("delete"); } @Test public void mark_deleted() { System.out.println("mark_deleted"); } @Test public void mark_modified() { System.out.println("mark_modified"); } @Test public void update() { System.out.println("update"); } @Test public void reset() { System.out.println("reset"); } } |
Expected execution order is:
Maven Test
[wp_ad_camp_3]
Here is a screenshot from maven test via command line console:
Download the Codes
https://github.com/Turreta/junit4-fixmethodorder-example