Spring Builders

Michael Isvy
Michael Isvy

Posted on

Do you clean up after you're done?

I think we're all used to using @Transactional inside our JUnit tests, so the database can remain in a clean state.

This article takes a different position, saying that each test should use some unique data, and therefore you don't need to rollback after a test: https://arialdomartini.github.io/when-im-done-i-dont-clean-up

Wondering if anybody follows those practices?

Top comments (2)

inabumstein profile image
Ina Bumstein

Both approaches cleaning up (using @Transactional
or dedicated deletion logic) and insuring that test only rely on data it creates has their benefits. I like my tests being independent from other tests activities. When test itself creates unique data in DB and logic under test needs only it you no longer need to do cleaning up the state before the test or rely that all tests leave proper DB state.
What I have noticed that it is less likely to have flaky tests when each test uses its own data. Surely it is not always possible as it depends on your application logic.

shardul profile image
Shardul Lavekar

I am not sure how not cleaning up helps in the below cases I have come across.

A test for user registration may fail inconsistently if previous test data is not cleared, leading to duplicate entries and false negatives.

If test A creates a user and test B assumes a clean state, leftover data from test A can cause test B to fail unexpectedly.

I wrote a few payments integration tests and those tests needed a clean environment to verify behavior without interference from old, irrelevant data.

I always found it easy to debug an isolated failed test knowing fully well that residual data has nothing to do with the failure.