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

查看:486
本文介绍了如何在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(){}
}

我想确保运行 test1() test2()之前每次运行 MyTest ,但我无法'找到像 @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假定所有测试都可以执行以任意顺序。来自FAQ:

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天全站免登陆