💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
# JUnit 有序测试执行示例 > 原文: [https://howtodoinjava.com/junit/ordered-testcases-execution-in-junit-4/](https://howtodoinjava.com/junit/ordered-testcases-execution-in-junit-4/) 编写 **JUnit 有序测试**案例被认为是[不良做法](https://howtodoinjava.com/best-practices/unit-testing-best-practices-junit-reference-guide/)。 但是,如果仍然遇到测试用例排序是唯一出路的情况,则可以使用`MethodSorters`类。 ## 1\. JUnit 方法排序器 从 JUnit4.11 版本开始引入`MethodSorters`。 此类声明了三种执行顺序,可以在测试用例中使用它们。 1. **`MethodSorters.DEFAULT`** – 以确定但不可预测的顺序对测试方法进行排序。 2. **`MethodSorters.JVM`** - 按照 JVM 返回的顺序保留测试方法。 3. **`MethodSorters.NAME_ASCENDING`** – **按方法名称**依字典顺序对测试方法进行排序,并使用`Method.toString()`作为平局。 ## 2\. JUnit 有序测试示例 – `NAME_ASCENDING` 让我们看看如何在 JUnit 中编写和执行有序的测试。 ```java import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; //Running test cases in order of method names in ascending order @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OrderedTestCasesExecution { @Test public void secondTest() { System.out.println("Executing second test"); } @Test public void firstTest() { System.out.println("Executing first test"); } @Test public void thirdTest() { System.out.println("Executing third test"); } } ``` 程序输出。 ```java Executing first test Executing second test Executing third test ``` ## 2\. JUnit 有序测试示例 – JVM 现在使用`JVM`选项执行相同的测试。 ```java package corejava.test.junit; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; //Running test cases in order of method names in ascending order @FixMethodOrder(MethodSorters.JVM) public class OrderedTestCasesExecution { @Test public void secondTest() { System.out.println("Executing second test"); } @Test public void firstTest() { System.out.println("Executing first test"); } @Test public void thirdTest() { System.out.println("Executing third test"); } } ``` 程序输出: ```java Executing third test Executing first test Executing second test ``` 显然,只有`NAME_ASCENDING`顺序可让您控制真正的顺序,而其他两个选项在**测试执行顺序序列**中对于开发人员而言却无法提供足够的可预测性。 在此 [JUnit 教程](https://howtodoinjava.com/junit-5-tutorial/)中,我们学习了编写 **JUnit 顺序测试**的过程。 让我知道你的想法。 学习愉快! 参考: [`MethodSorters`类](https://junit.org/junit4/javadoc/4.12/org/junit/runners/MethodSorters.html)