如何在 JUnit4 中按特定顺序运行测试方法? [英] How to run test methods in specific order in JUnit4?

查看:30
本文介绍了如何在 JUnit4 中按特定顺序运行测试方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以特定的顺序执行由@Test注解的测试方法.

I want to execute test methods which are annotated by @Test in specific order.

例如:

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

我想确保每次运行MyTest时在test2()之前运行test1(),但我找不到注释比如@Test(order=xx).

I want to ensure to run test1() before test2() each time I run MyTest, but I couldn't find annotation like @Test(order=xx).

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

I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?

推荐答案

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

I think it's quite important feature for JUnit, if author of JUnit doesn't want the order feature, why?

我不确定使用 JUnit 是否有一种干净的方法可以做到这一点,据我所知,JUnit 假定所有测试都可以按任意顺序执行.来自常见问题解答:

I'm not sure there is a clean way to do this with JUnit, to my knowledge JUnit assumes that all tests can be performed in an arbitrary order. From the FAQ:

(...) 测试方法调用的顺序不能保证,因此 testOneItemCollection() 可能在 testEmptyCollection() 之前执行.(...)

How do I use a test fixture?

(...) The ordering of test-method invocations is not guaranteed, so testOneItemCollection() might be executed before testEmptyCollection(). (...)

为什么会这样?好吧,我相信让测试顺序依赖是作者不想提倡的一种做法.测试应该是独立的,它们不应该耦合在一起,违反这一点使事情更难维护,会破坏单独运行测试的能力(显然)等.

Why is it so? Well, I believe that making tests order dependent is a practice that the authors don't want to promote. Tests should be independent, they shouldn't be coupled and violating this will make things harder to maintain, will break the ability to run tests individually (obviously), etc.

话虽如此,如果您真的想朝这个方向发展,请考虑使用 TestNG,因为它支持以任意顺序本机运行测试方法(并且诸如指定方法之类的事情取决于方法组).Cedric Beust 以testng 中测试的执行顺序解释了如何做到这一点.

That being said, if you really want to go in this direction, consider using TestNG since it supports running tests methods in any arbitrary order natively (and things like specifying that methods depends on groups of methods). Cedric Beust explains how to do this in order of execution of tests in testng.

这篇关于如何在 JUnit4 中按特定顺序运行测试方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆