这是一篇译文,原文也很短,如下:
By design, JUnit does not specify the execution order of test method invocations. Until now, the methods were simply invoked in the order returned by the reflection API. However, using the JVM order is unwise since the Java platform does not specify any particular order, and in fact JDK 7 returns a more or less random order. Of course, well-written test code would not assume any order, but some do, and a predictable failure is better than a random failure on certain platforms.
From version 4.11, JUnit will by default use a deterministic, but not predictable, order (MethodSorters.DEFAULT)
. To change the test execution order simply annotate your test class using @FixMethodOrder
and specify one of the available MethodSorters:
@FixMethodOrder(MethodSorters.JVM)
: Leaves the test methods in the order returned by the JVM. This order may vary from run to run.
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
: Sorts the test methods by method name, in lexicographic order.
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {
@Test
public void testA() {
System.out.println("first");
}
@Test
public void testB() {
System.out.println("second");
}
@Test
public void testC() {
System.out.println("third");
}
}
Above code will execute the test methods in the order of their names, sorted in ascending order
之前准备做安卓app的UI自动化测试时,在使用robotium的过程中,也用到了junit,过了一段时间,有点生疏,通过这次翻译,也把这方面的知识温习一下,
下面是译文,水平有限,勿喷:
JUnit一个测试类中测试方法的执行顺序
按设计,JUnit并不指定测试方法调用的执行顺序。到目前为止,测试方法只是简单地按照反射API返回的顺序被调用。然而,由于Java平台并没有指定特定的顺序,使用JVM顺序并不明智。实际上,JDK 7返回的几乎是随机顺序。当然,好的测试代码并不会假定任何的执行顺序,但是也有些会。并且,在特定的平台上,一个可预见的失败要好于随机的失败。