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

例如:

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

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

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


当前回答

下面是JUnit的一个扩展,可以生成所需的行为:https://github.com/aafuks/aaf-junit

我知道这与JUnit哲学的作者相违背,但是当在没有严格单元测试的环境中使用JUnit时(如在Java中实践的那样),这将非常有帮助。

其他回答

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

如果您摆脱了现有的Junit实例,并在构建路径中下载Junit 4.11或更高版本,以下代码将按照它们的名称(升序排序)执行测试方法:

import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class SampleTest {

    @Test
    public void testAcreate() {
        System.out.println("first");
    }
    @Test
    public void testBupdate() {
        System.out.println("second");
    }
    @Test
    public void testCdelete() {
        System.out.println("third");
    }
}

对于JUnit 4,将这个注释放在测试类上解决了这个问题。

@FixMethodOrder(MethodSorters.JVM)

你可以使用这些代码中的一段: @FixMethodOrder(MethodSorters.JVM)或@FixMethodOrder(MethodSorters.DEFAULT)或@FixMethodOrder(MethodSorters.NAME_ASCENDING)

在你的测试类之前,像这样:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class BookTest {...}

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