Reputation: 2564
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 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.
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?
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.
Upvotes: 3
Views: 12806
Reputation: 20102
As a best practice I would recommend to clear your data storage between every test, to guarantee each test is isolated from other tests.
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.
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.
Upvotes: 2
Reputation: 4675
It depends on how much you adhere to the Don't Repeat Yourself principle. It's also worth remembering that you have @After
called after each @Test
and @AfterClass
called after all the @Test
have run. With this granularity, it should be simple to remove duplication but still split those tasks that should only run at the very end, or after each test.
Upvotes: 4