在項(xiàng)目中寫JunitTest類時(shí)跷究,test的運(yùn)行順序默認(rèn)是指定的肴掷,不變的块蚌,但是這個(gè)順序是無法預(yù)估的机蔗。有時(shí)候我們想要手動(dòng)去指定Test的運(yùn)行順序蒲祈,在org.junit包下有個(gè)類@FixMethodOrder
,這個(gè)注解類可以傳入一個(gè)參數(shù)MethodSorters
萝嘁,具體的代碼如下:
package org.junit.runners;
import java.lang.reflect.Method;
import java.util.Comparator;
import org.junit.internal.MethodSorter;
/**
* Sort the methods into a specified execution order.
* Defines common {@link MethodSorter} implementations.
*
* @since 4.11
*/
public enum MethodSorters {
/**
* Sorts the test methods by the method name, in lexicographic order,
* with {@link Method#toString()} used as a tiebreaker
*/
NAME_ASCENDING(MethodSorter.NAME_ASCENDING),
/**
* Leaves the test methods in the order returned by the JVM.
* Note that the order from the JVM may vary from run to run
*/
JVM(null),
/**
* Sorts the test methods in a deterministic, but not predictable, order
*/
DEFAULT(MethodSorter.DEFAULT);
private final Comparator<Method> comparator;
private MethodSorters(Comparator<Method> comparator) {
this.comparator = comparator;
}
public Comparator<Method> getComparator() {
return comparator;
}
}
但是需要注意的是梆掸,這個(gè)值在junit 4.11后才有。
在gradle運(yùn)行時(shí)酿愧,有可能不生效沥潭,可能是junit版本比較低。
-
MethodSorter.DEFAULT
按照一個(gè)固定的順序指定嬉挡,但是這個(gè)順序不可以預(yù)知。
-
MethodSorter.NAME_ASCENDING
按照方法名字升續(xù)進(jìn)行排序執(zhí)行
-
MethodSorter.JVM
jvm隨機(jī)運(yùn)行