Executing JUnit tests in Order
By design, JUnit does not specify the execution order of test method invocations. The JUnit runner depends on reflection to execute the tests. The JVM does not specify any particular order and could be random. Normally this should not be a problem, cause well written tests would not assume any order, but some do.
JUnit 4.11 provides us with an @FixMethodOrder
annotation to specify the execution order. There are three options to change the execution order.
MethodSorters.DEFAULT
Use a deterministic, but not predictable order returned by the JVM.MethodSorters.NAME_ASCENDING
Sorts the test methods by method name in lexicographic order.MethodSorters.JVM
execute test methods in the order returned by the JVM. Varies from run to run.
package com.memorynotfound.test;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestExecutionOrder {
@Test
public void testB(){
System.out.println("b");
}
@Test
public void testA(){
System.out.println("a");
}
@Test
public void testC(){
System.out.println("c");
}
}
The previous code generates the following junit tests in order.
a
b
c