Video in progress

Senior 🧪 Testing

How do you choose a database cleanup strategy between integration tests: rollback, TRUNCATE, or separate data per test?

At the repository level, the test transaction rollback is fast and enough. When a commit, another thread or RANDOM_PORT is involved, use a single TRUNCATE ... CASCADE before the test. If you need to run in parallel, the best approach is not to rely on cleanup at all: each test creates its own unique data.

📖 Answer

Every strategy has a cost:

Strategy Speed What it hides Parallel
Test @Transactional rollback fastest commits, AFTER_COMMIT, other threads yes, each test in its own transaction
TRUNCATE before each test medium almost nothing no, shared database
Unique data, no cleanup fast nothing yes
A separate database per fork fast nothing yes, at the fork level

When I TRUNCATE, I do it in a single statement, in @BeforeEach, not in @AfterEach. That way the data of a failed test stays in the database and you can open it up and look:

@BeforeEach
void cleanDb(@Autowired JdbcTemplate jdbc) {
    jdbc.execute("""
        TRUNCATE orders, order_items, payments, enrollments
        RESTART IDENTITY CASCADE
        """);
}

The list doesn't include flyway_schema_history or reference tables (currencies, roles). Keeping table names by hand goes stale; it's better to read them once from information_schema and cache them. deleteAll() is slow and depends on FK order.

The unique data approach scales best: the test doesn't check count() == 1 but "the order I created", and emails and slugs have a random suffix. Tests like this can run in parallel on one database and don't care about garbage another test left behind.

In a very big suite I make a separate database per Surefire/Gradle fork: in PostgreSQL, CREATE DATABASE test_fork_3 TEMPLATE app_template copies a migrated template database in a few seconds.

A mixed strategy is normal: repository tests with rollback, HTTP and asynchronous flows with TRUNCATE or unique data. What matters is that it's decided once in a single base class, not each test class having its own way.