JUnit测试用例@Before和@After批注 [英] JUnit Test Cases @Before and @After annotations
问题描述
我们按照以下做法为我们的方法编写JUnit测试.
We are following below practices to write JUnit tests for our methods.
-
每个方法将拥有自己的类,该类包含该方法所需的所有测试.例如:类测试{...}
Each method will be having their own class which holds all the tests which are required for that method. For e.g.: class test {...}
@Before将包含按条件设置的诸如实体"之类的方法,因此当我们执行编辑"时,不需要复制/粘贴用于在每个方法级别添加实体的代码.
@Before will consists of per-requisites setup for methods like "Entity" so that when we do Edit we don't need to copy/paste code for adding an entity at each method level.
现在我的问题是,我们应该删除通过在@after方法中将代码写入垃圾测试数据而输入的所有数据吗?
Now here my question is, shall we delete all the data which we entered by writing code to trash test-data in @after method or just let it be?
我知道我们可以使其变得可配置,但是什么是最佳实践?保留或删除它.根据我的直觉,感觉删除应该更好,好像在db中已经有一些重复数据一样-可能会触发错误的true或false.
I know we can make it configurable but what is best practice? keep it or delete it. As per my gut feeling deleting should be better as if there is some duplicate data already in db - it may trigger wrong true or false.
推荐答案
作为最佳实践,我建议清除每个测试之间的数据存储,以确保每个测试都与其他测试隔离.
As a best practice I would recommend to clear your data storage between every test, to guarantee each test is isolated from other tests.
如果要保持某些设置有效(例如,从@BeforeClass
开始),可以使用@After
方法完成.也可以在@Before
方法中完成此操作,例如,为每个测试用新实例覆盖变量,如果这样做,则在测试之后无需清理.
This could be done with the @After
method if you want to keep some of the settings alive (from the @BeforeClass
for example). It could also be done in the @Before
method for example by overriding variables with a new instance for every test, if you do so you do not need a clean up after the tests.
要清理@BeforeClass
方法的设置,应使用@AfterClass
例如关闭数据库连接或类似的连接,而只需执行一次即可.但这并不是每种单元测试都需要的.
To clean up your settings of the @BeforeClass
method you should use @AfterClass
for example to close a Database connection or something simular what only needed to be done once. But this is not needed for every kind of unit test.
这篇关于JUnit测试用例@Before和@After批注的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!