deej
deej

Reputation: 2564

JUnit Test Cases @Before and @After annotations

We are following below practices to write JUnit tests for our methods.

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

Answers (2)

Simulant
Simulant

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 @BeforeClassfor 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

imrichardcole
imrichardcole

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

Related Questions