By
default, junit do not specify the execution order of the test cases (Order of
execution depends on the order returned by the reflection API).
Junit
provides '@FixMethodOrder' annotation, to order the execution of test cases.
Example
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public
class TestApp {
}
In
the above example, test cases in TestApp class will execute in lexicographic
order.
MethodSorters
is an enumerator, provides below constants.
NAME_ASCENDING: Sorts the test
methods by the method name, in lexicographic order.
JVM: Execute test methods
in the order returned by the JVM.
DEFAULT: Sorts the test
methods in a deterministic, but not predictable, order
When
I check the code, the default method sorter is implemented like below.
public static final Comparator<Method>
DEFAULT = new Comparator<Method>() {
public int compare(Method m1, Method
m2) {
int i1 = m1.getName().hashCode();
int i2 = m2.getName().hashCode();
if (i1 != i2) {
return i1 < i2 ? -1 : 1;
}
return NAME_ASCENDING.compare(m1,
m2);
}
};
Find
the below working application.
TestApp.java
package com.sample.test; import static org.junit.Assert.assertTrue; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class TestApp { @Test public void testCase3() { System.out.println("Executing test case 3"); assertTrue(true); } @Test public void testCase2() { System.out.println("Executing test case 2"); assertTrue(true); } @Test public void testCase4() { System.out.println("Executing test case 4"); assertTrue(true); } @Test public void testCase1() { System.out.println("Executing test case 1"); assertTrue(true); } @Test public void testCase5() { System.out.println("Executing test case 5"); assertTrue(true); } }
When
you ran above class, you can able to see below messages in the console.
Executing
test case 1
Executing
test case 2
Executing
test case 3
Executing
test case 4
Executing test case 5
No comments:
Post a Comment