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.
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
@Aftermethod if you want to keep some of the settings alive (from the@BeforeClassfor example). It could also be done in the@Beforemethod 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
@BeforeClassmethod you should use@AfterClassfor 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.