user3510462
user3510462

Reputation: 35

Accessing same instance of an object in @Before and @After in a JUnit4 test

I'm using JUnit 4 for testing a database-application. Since each test requires a special preset of the database before it runs, I'm using the @Before method to load the data first and the @After method to delete all data from the database. For some reasons I cannot use DBUnit, but I have to use some custom Java implementation that will do the work of the database loading and cleanup. While I can create an instance of a class from this custom implementation in the @Before method, it is important that I get the same instance in the @After method.

My first idea was to use a field (e.g., myObject) in the test class and set it in the @Before method, so I can use it in the @After method again. However, I'm not sure about the JUnit lifecycle and how it will behave when tests run in parallel, i.e. if myObject will be overwritten.

Another idea is to use a JUnit TestWatcher that creates an instance of this object in the starting method and saves it in a field, too. Then I use @Rule in my test class to access this instance via a getter method in the TestWatcher implementation.

So my questions are basically:

1) Is it good practice to preset the database in the @Before method and delete all data in the @After method? So if the next test requires only a small amount of data to be loaded, it will run much faster.

2) How can I access the same instance of an object in the @After method that was created in the @Before method. It must be guaranteed that it is the same instance, even if tests run in parallel. Is any of my two ideas a good way to implement it, which is better?

Thanks!

Upvotes: 0

Views: 801

Answers (1)

JB Nizet
JB Nizet

Reputation: 691765

  1. IMHO, no. The good practice, that I recommend when using DbSetup (see http://dbsetup.ninja-squad.com/user-guide.html#dont-cleanup-prepare for a more detailed explanation), is to clear the database and insert the necessary data before the test, and do nothing after the test. That way, you're sure that the database contains exactly what you want when starting a test (even if a previous one failed to cleanup), and you can inspect the database after a failed test, in order to diagnose problems.

  2. Use a field. JUnit creates a new instance of the test class per test.

Upvotes: 3

Related Questions