我想以特定的顺序执行@Test注释的测试方法。

例如:

public class MyTest {
    @Test public void test1(){}
    @Test public void test2(){}
}

我想确保每次运行MyTest时都在test2()之前运行test1(),但我找不到@Test(order=xx)这样的注释。

我认为这对JUnit来说是非常重要的功能,如果JUnit的作者不想要订单功能,为什么?


当前回答

如果希望在JUnit 5中以特定顺序运行测试方法,可以使用下面的代码。

@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class MyClassTest { 

    @Test
    @Order(1)
    public void test1() {}

    @Test
    @Order(2)
    public void test2() {}

}

其他回答

请看我的解决方案: “Junit和java 7。”

在本文中,我将描述如何按顺序运行junit测试——“就像在源代码中那样”。 测试将按照测试方法在类文件中出现的顺序运行。

http://intellijava.blogspot.com/2012/05/junit-and-java-7.html

但正如Pascal Thivent所说,这不是一个好的做法。

使用JUnit 5.4,你可以指定顺序:

@Test
@Order(2)
public void sendEmailTestGmail() throws MessagingException {

你只需要注释你的类

@TestMethodOrder(OrderAnnotation.class)

https://junit.org/junit5/docs/current/user-guide/#writing-tests-test-execution-order

我在我的项目中使用这个,它工作得非常好!

(尚未发布的)更改https://github.com/junit-team/junit/pull/386引入了@SortMethodsWith。https://github.com/junit-team/junit/pull/293至少使顺序可以预测(在Java 7中,它可以是相当随机的)。

请看这个:https://github.com/TransparentMarket/junit。它按照指定的顺序(在已编译的类文件中定义)运行测试。此外,它还提供了一个AllTests套件,可以首先运行由子包定义的测试。使用AllTests实现还可以扩展过滤属性的解决方案(我们过去使用@Fast注释,但这些注释还没有发布)。

JUnit从5.5开始允许在类上使用@TestMethodOrder(OrderAnnotation.class),在测试方法上使用@Order(1)。

JUnit旧版本允许测试方法使用类注释有序运行:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
@FixMethodOrder(MethodSorters.JVM)
@FixMethodOrder(MethodSorters.DEFAULT)

默认情况下,测试方法按字母顺序运行。所以,为了设置特定的方法,你可以像这样命名它们:

a_TestWorkUnit_WithCertainState_ShouldDoSomething b_TestWorkUnit_WithCertainState_ShouldDoSomething c_TestWorkUnit_WithCertainState_ShouldDoSomething

Or

_1_TestWorkUnit_WithCertainState_ShouldDoSomething _2_TestWorkUnit_WithCertainState_ShouldDoSomething _3_TestWorkUnit_WithCertainState_ShouldDoSomething

你可以在这里找到例子。