Junit 4测试套件和个别测试类 [英] Junit 4 test suite and individual test classes

查看:100
本文介绍了Junit 4测试套件和个别测试类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有BeforeClass和AfterClass方法的JUnit 4测试套件,可对以下测试类进行设置/拆卸. 我需要的是也自己运行测试类,但是为此,我需要为每个测试类设置安装/拆卸方案(BeforeClass和AfterClass或类似的东西).问题是,当我运行套件时,我不想在每个测试类之前和之后执行设置/删除操作,而只想从测试套件中执行设置/删除操作(一次). 是否有可能 ?预先感谢.

I have a JUnit 4 test suite with BeforeClass and AfterClass methods that make a setup/teardown for the following test classes. What I need is to run the test classes also by them selves, but for that I need a setup/teardown scenario (BeforeClass and AfterClass or something like that) for each test class. The thing is that when I run the suite I do not want to execute the setup/teardown before and after each test class, I only want to execute the setup/teardown from the test suite (once). Is it possible ? Thanks in advance.

推荐答案

我不知道使用JUnit进行此操作的任何标准方法.您可能已经知道,这样做的原因是您的测试用例应彼此独立运行.这涉及在每种测试方法之前和之后运行的正常"设置/拆卸方法.但是,类的设置和删除是有些不同的-尽管我仍然希望独立运行测试并避免遇到麻烦.

I don't know of any standard way to do this with JUnit. The reason for it, as you probably already know, is that your test cases should run independently of each other. This concerns the "normal" setup/teardown methods which run before and after each test method. Class setup and teardown is a bit different though - although I would still prefer running my tests independently and staying out of the trouble zone.

但是,如果您真的确信自己在做什么,则可以使用全局标志来指示是否要运行类setup/teardown,并在类setup/teardown方法中检查其状态.在您的测试套件中,您可以包括一个特殊的类作为第一个类,它只执行安装程序并设置全局标志,以向实际的测试用例指示不得运行其类的setup/teardown方法.同样,套件中的一个特殊的最后一个类可以执行拆卸代码.需要注意的是,恐怕JUnit不能保证套件中测试类的执行顺序,尽管很可能它会按指定的顺序执行它们-但这只是实现细节.尝试一下,它可能对您有用-但不能保证它会一直做您期望的事情.

However, if you really are convinced of what you are doing, you could use a global flag to signal whether or not the class setup/teardown is to run, and to check for its state in the class setup/teardown methods. In your test suite, you could include a special class as the very first one, which does nothing more than execute the setup and set the global flag to indicate to the real test cases that their class setup/teardown methods must not be run. Similarly, a special last class in the suite can execute the teardown code. The caveat is that I am afraid JUnit does not guarantee the order of execution of test classes inside a suite, although most probably it does execute them in the specified order - but this is just an implementation detail. Try it out, it may work for you - but there is no guarantee it will always do what you expect.

这篇关于Junit 4测试套件和个别测试类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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