且构网

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

如何使用 Junit 按顺序运行测试方法

更新时间:2023-01-11 17:08:06

所以对于像这样的测试——步骤相互依赖——你应该真正将它们作为一个单元来执行.你真的应该做这样的事情:

So for tests like these - where the steps are dependent on each other - you should really execute them as one unit. You should really be doing something like:

@Test
public void registerWelcomeAndQuestionnaireUserTest(){
    // code
    // Register
    // Welcome
    // Questionnaire
}

正如@Jeremiah 下面提到的,有一些独特的方法可以使单独的测试无法预测地执行.

As @Jeremiah mentions below, there are a handful of unique ways that separate tests can execute unpredictably.

既然我已经说过了,这就是你的解决方案.

Now that I've said that, here's your solution.

如果你想要单独的测试,你可以使用 @FixMethodOrder 然后按 NAME_ASCENDING 执行.这是我知道的唯一方法.

If you want separate tests, you can use @FixMethodOrder and then do it by NAME_ASCENDING. This is the only way I know.

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestMethodOrder {

    @Test
    public void testA() {
        System.out.println("first");
    }
    @Test
    public void testC() {
        System.out.println("third");
    }
    @Test
    public void testB() {
        System.out.println("second");
    }
}

将执行:

testA(), testB(), testC()

在你的情况下:

@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class ThisTestsEverything{

    @Test
    public void T1_registerUser(){
        // code
    }

    @Test
    public void T2_welcomeNewUser(){
        // code
    }

    @Test
    public void T3_questionaireNewUser(){
        // code
    }

}