【问题标题】:Run JUnit SuiteClasses in a random order以随机顺序运行 JUnit SuiteClasses
【发布时间】:2016-01-11 08:46:30
【问题描述】:

我最近开始将我的 JUnit 测试分组到测试套件中。到目前为止,这对我来说非常好。我唯一的抱怨是@SuiteClasses 注释的顺序决定了测试执行的顺序。我知道这是它的预期方式,但我只想使用测试套件对测试进行分组,而不是对它们进行排序。

由于我们在自动化、功能性 (Selenium) 测试环境中使用这些测试,因此我不希望测试始终以相同的顺序执行。有谁知道如何仅将测试套件用于他们的分组功能?

提前致谢!

我在下面添加了我的代码:

@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class, Test3.class})
public class TestSuite {
private static ScreenRecorder screenRecorder;

@BeforeClass
public static void setUp() {
    screenRecorder = new ScreenRecorder(1, Data.SCREENSHOT_DIR);
    screenRecorder.startRecording(TestSuite.class.getCanonicalName());
}

@AfterClass
public static void tearDown() throws InterruptedException, CommandException {
    screenRecorder.stopRecording();
}

}

【问题讨论】:

    标签: java junit automated-tests functional-testing


    【解决方案1】:

    您需要为所有测试用例使用特定的 JUnit 运行器。

    这是我前段时间写的一篇:

    public class RandomTestRunner extends BlockJUnit4ClassRunner {
    
        public RandomTestRunner(Class<?> clazz) throws InitializationError {
            super(clazz);
        }
    
        @Override
        protected List<FrameworkMethod> computeTestMethods() {
            List<FrameworkMethod> methods = super.computeTestMethods();
            List<FrameworkMethod> newMethods = new ArrayList<>(methods);
            Collections.shuffle(newMethods);
            return newMethods;
        }
    }
    

    然后,您需要将@RunWith(RandomTestRunner.class) 注释添加到您想要真正随机运行的所有测试用例类中,因此在您的情况下为Test1Test2Test3

    您的套件的顺序仍然相同:Test1 然后Test2 然后Test3,只有这些类中的测试是随机的。

    【讨论】:

    • 我的测试方法已经以随机顺序运行,我希望测试类也被打乱,所以这不会奏效。还是谢谢你:)
    • 是的,我就是这么想的。我尝试扩展 Suite 类,但无法以简单的方式重新组织它们的顺序。我认为这可以通过访问Suite.runners 变量并在Suite 构造函数中的第一次初始化之后设置其值来以一种混乱的方式完成,但这需要一些我不太喜欢的反射用法……
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 1970-01-01
    • 2017-02-18
    • 2021-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    相关资源
    最近更新 更多