# （六）JUnit 用例执行顺序




在运行测试的过程中，有时候需要控制用例的执行顺序。

#### @FixMethodOrder
----
JUnit 通过 __@FixMethodOrder__ 注解来控制测试方法的执行顺序的。__@FixMethodOrder__ 注解的参数是 __org.junit.runners.MethodSorters__ 对象,在枚举类 __org.junit.runners.MethodSorters__ 中定义了如下三种顺序类型：

* MethodSorters.JVM

> 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得到的方法顺序，也就是代码中定义的方法顺序)

* MethodSorters.DEFAULT(默认的顺序)

> Sorts the test methods in a deterministic, but not predictable, order() (以确定但不可预期的顺序执行)

* MethodSorters.NAME_ASCENDING

> Sorts the test methods by the method name, in lexicographic order, with Method.toString() used as a tiebreaker (按方法名字母顺序执行)

#### 例子
---
具体如何使用，看例子，创建 TestRunSequence 测试类。

```java
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
import static org.junit.Assert.assertEquals;

// 按字母人顺序执行
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestRunSequence {

    @Test
    public void TestCase1() {
        assertEquals(2+2, 4);
    }

    @Test
    public void TestCase2() {
        assertEquals(2+2, 4);
    }

    @Test
    public void TestAa() {
        assertEquals("hello", "hi");
    }
}

```

__MethodSorters.NAME_ASCENDING__ 设置按字母的顺序执行，所以，__TestAa()__ 先被执行，虽然它在代码中是最后一条用例。

__运行结果如下：__

![](http://img.testclass.net/junit_run_result_3.png)




原始封面

![课程图片](https://images.unsplash.com/photo-1581089787571-e2358b118e7a?w=300)


