且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Intellij中定义运行junit测试的顺序?

更新时间:2023-11-19 23:31:46

根据 JUnit的维基


按照设计,JUnit不指定测试方法
调用的执行顺序。到目前为止,这些方法只是按反射API返回的
顺序调用。但是,使用JVM顺序是不明智的
,因为Java平台没有指定任何特定的顺序,而在
中,JDK 7会返回或多或少的随机顺序。当然,
编写良好的测试代码不会假设任何订单,但有些会这样做,并且
可预测的失败优于某些
平台上的随机失败。

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.

从版本4.11开始,JUnit默认使用确定性但不是
可预测的顺序(MethodSorters.DEFAULT)。要更改测试
执行顺序,只需使用@FixMethodOrder
注释您的测试类,并指定一个可用的MethodSorters:

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):将测试方法保留在JVM返回的
顺序中。此订单可能因运行而异。

@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):对测试方法进行排序
按方法名称,按字典顺序排列。

@FixMethodOrder(MethodSorters.NAME_ASCENDING): Sorts the test methods by method name, in lexicographic order.

您可以使用 MethodSorters.NAME_ASCENDING 并更改您的方法名称以符合您的特定订单。我知道你只是为了调试而使用它,但它依赖于你的测试方法执行顺序 Test Smell 而且JUnit不能提供更精细的谷物控制测试方法执行顺序

You could use MethodSorters.NAME_ASCENDING and change your method names to match with your specific order. I know you're using this just for debugging sake but it's a Test Smell to rely on your test methods execution order and JUnit does not provide more finer grain control over test methods execution order