Test execution order——junit4测试用例的执行顺序

这是一篇译文,原文也很短,如下:

Test execution order

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.

Example

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返回的几乎是随机顺序。当然,好的测试代码并不会假定任何的执行顺序,但是也有些会。并且,在特定的平台上,一个可预见的失败要好于随机的失败。
        从4.1.1版本开始,JUnit默认会使用一个确定的,但不可预知的顺序(MethodSorters.DEFAULT)。可以通过给你的测试类添加注解@FixMethodOrder来改变这个执行顺序,可以在下面可选的MethodSorter中任意指定一个:
@FixMethodOrder(MethodSorters.JVM): 使用JVM返回的顺序,这个顺序可能每次执行都不一样
@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");
    }
}
以上代码将按照测试方法名称升序排列的顺序执行这些测试方法。

你可能感兴趣的:(junit)