简体   繁体   English

JUnit以与文件相同的顺序运行方法

[英]JUnit run the methods in the same order as in file

Hi I have a requirement to run one of my test methods after certain method completed. 嗨我需要在某些方法完成后运行我的一个测试方法。 Even though tests should be independent as per How to run test methods in specific order in JUnit4? 即使测试应该是独立的, 如何在JUnit4中按特定顺序运行测试方法? .

There is a another hack for this is to use the 另一个黑客就是使用它

@FixMethodOrder(MethodSorters.NAME_ASCENDING) @FixMethodOrder(MethodSorters.NAME_ASCENDING)

But what I want is I need to run the tests in the order same as in the file. 但我想要的是我需要按照与文件相同的顺序运行测试。 If it cannot be done, then I just have to live with Method Name sorters 如果无法完成,那么我只需使用方法名称分类器

Since Java 7, the JDK no longer guarantees the order in which methods in a class will be returned when looked up via reflection (as a framework like JUnit must do). 从Java 7开始,JDK不再保证在通过反射查找时返回类中的方法的顺序(像JUnit这样的框架必须这样做)。

Thus, the answer to your question is: No, it is not possible to ensure that test methods are executed in the order in which they are declared in source code. 因此,您的问题的答案是: 不,不可能确保测试方法按照在源代码中声明的顺序执行。

As you noticed, the only alternative to potentially random ordering is @FixMethodOrder(MethodSorters.NAME_ASCENDING) in JUnit 4 on JDK 7+. 正如您所注意到的,可能随机排序的唯一替代方法是JDK 7+上的JUnit 4中的@FixMethodOrder(MethodSorters.NAME_ASCENDING)

There is a very crucial point, why you shouldn't start to invent such requirements. 有一个非常关键的问题,为什么你不应该开始发明这样的要求。

The idea of unit tests is that each test ... tests a different aspect of your class under test. 单元测试的想法是每个测试......测试你所测试的类的不同方面。 Aspects that are independent of each other. 相互独立的方面。 That is the one side. 这是一方面。 The other is: unit tests exist to help you to determine problems in your production as quickly as possible. 另一种是:单元测试存在,以帮助您尽快确定你的生产问题。

Meaning: when all of a sudden, a unit test is failing (because somebody changed something somewhere), then you want to find the root cause of this problem as soon as possible. 含义:突然间,单元测试失败了(因为有人在某处改变了某些东西),那么你想尽快找到这个问题的根本原因。 Anything that prevents you from getting to that goal makes your unit test less valuable to you! 任何阻止你达到目标的东西都会让你的单元测试对你来说变得不那么有价值!

Things that make it harder for you to find the foot cause would be: 让你更难找到足部原因的事情是:

  1. extensive "externalized" setup - when you start using (too much) inheritance for your test cases 广泛的“外部化”设置 - 当您开始为您的测试用例使用(太多)继承时
  2. complicated relations between your test methods (like: your idea) 你的测试方法之间的复杂关系(比如:你的想法)

Long story short: unit tests are not meant to be run in any specific order. 长话短说:单元测试不是以任何特定顺序运行。 So, instead of spending a lot of time pushing JUnit into a corner where it doesn't want to be ... step back for a second, and reconsider why you think you need things to be that way. 因此,不要花费大量时间将JUnit推到一个不想成为的角落......退一步,并重新考虑为什么你认为你需要这样的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM