user3060230
user3060230

Reputation: 181

Cleanup after all JUnit test runs

In my project I have to do some repository setup before all tests and after successful tests I want to clean up, I know @afterClass is used for this but it requires static variables but i dont want to make my objects statics, so is there any other way by which I can achieve this??

Upvotes: 0

Views: 5656

Answers (2)

Zoltán
Zoltán

Reputation: 22156

If you want set up and tear down before and after each test method, use @Before and @After. If you want to set up once, run all your tests and then tear down, use @BeforeClass and @AfterClass.

Yes, @BeforeClass and @AfterClass are static methods, but note that JUnit recreates your test class instance for each test method, so you cannot maintain any information in non-static fields of a test class across different tests.

I, as the other commenters here, have a feeling that you want to avoid static fields because there's a common opinion that they are bad practice. Please note, however, that good practice in writing code often does not apply to good practice in writing tests. This is one such example.

Upvotes: 2

Erik Madsen
Erik Madsen

Reputation: 2014

If you're using JUnit4, then use @After. Documentation here. Note that your methods annotated this way will be executed after each test case, in a similar fashion to @Before being executed before each test case.

If you're writing an integration test with multiple test cases and your setup is heavy, you could use a combination of @BeforeClass to set up static objects and @After to mutate/clean up/reset certain parts of these objects' states. This, of course, would violate your requirement of not using static variables, but I can't really see the rationale behind that requirement. Recall that JUnit instantiates the test class once for every single test case.

Upvotes: 2

Related Questions