Quick revision
The short answer
Each test owns its data: it creates the rows it needs with unique identifiers, such as a random tenant or customer id, and every query and assertion filters by those ids instead of counting the whole table. No test deletes data globally; a test cleans up only what it created, or the suite gives each test class its own schema. Reference data that every test needs is loaded once by the migrations and treated as read-only.
What to remember
In this answer, we designed test data for parallel tests on one shared container. Each test creates its own data with unique identifiers, ideally a tenant of its own, and every assertion filters by those ids instead of counting whole tables. Global cleanup is removed; tests delete only their own rows or leave them for the throwaway container. Reference data comes from migrations and is read-only, and the few tests that need the whole database get their own schema or run in a separate sequential phase.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Each test owns its data: it creates the rows it needs with unique identifiers, such as a random tenant or customer id, and every query and assertion filters by those ids instead of counting the whole table. No test deletes data globally; a test cleans up only what it created, or the suite gives each test class its own schema. Reference data that every test needs is loaded once by the migrations and treated as read-only.
Why this question is asked
Running integration tests in parallel is one of the cheapest ways to cut a 20 minute suite to 6 minutes, and sharing one database container keeps the start-up cost low. But the moment two tests run at the same time against the same tables, every shortcut we took in a sequential suite turns into a random failure. Interviewers ask this design question because it tests whether we can think about isolation as a property of the data, not of the timing. In this answer, we will see what goes wrong when sequential tests run in parallel, then build the strategy step by step: unique ids, ownership of cleanup, read-only reference data, assertions scoped to the test, and the per-schema option for the tests that cannot follow those rules.
1What Breaks When Tests Run in Parallel
Start with a typical sequential suite. Each test assumes the tables are empty when it starts, inserts a customer with email ann@example.com, checks that the customer count is 1, and truncates the tables at the end. Run sequentially, that works perfectly.
Now enable parallel execution in JUnit 5 and run four test classes at once against the same PostgreSQL container. Test A inserts ann@example.com, test B inserts ann@example.com a millisecond later and hits the unique constraint. Test C counts customers and finds 3 instead of 1. Test D finishes first and truncates everything, deleting the rows that A and B are still using. Each failure depends on timing, so the suite is now flaky rather than broken, which is worse, because the failures are hard to reproduce.
The configuration above runs test classes concurrently while the methods inside a class run one after another, which is a common, gentle first step. Whatever the setting, the fix is the same: tests must stop assuming they are alone.
2Rule 1: Every Test Creates Its Own Data With Unique Ids
The foundation is that each test creates exactly the data it needs, and makes it unique. A random suffix on every natural key, such as an email, an order number or a tenant id, means two tests can never collide on a unique constraint, and each test can find its own rows later.
If the domain is multi-tenant, a unique tenant per test is the most powerful version of this rule, because almost every query in the application already filters by tenant. The test then lives in its own small world inside the shared database without any extra effort. Database-generated ids are already unique, so they need no special handling; the rule is about values the test chooses.
3Rule 2: Clean Up Only What You Created
Global cleanup is the next thing to remove. TRUNCATE, DELETE FROM orders without a condition, or a Flyway clean before each test all destroy other tests' data in the middle of their run. There are two safe alternatives. The first is that a test deletes only its own rows, by its unique ids, in an @AfterEach method. The second is to not clean up at all: with unique ids, leftover rows from earlier tests do no harm, and the container is thrown away at the end of the run anyway.
Many teams choose the second option and are surprised by how well it works. It is fast, it cannot delete someone else's data, and when a test fails, its rows are still there to inspect. The only thing to watch is tests that do a lot of work with growing data, where a large table could slow later queries; for a test run that lasts minutes this rarely matters.
Rolled-back test transactions are a third option for tests that run fully on the test thread, such as @DataJpaTest classes. Uncommitted rows are invisible to other tests, so they cannot collide. They do not help for tests that call the application over HTTP or through message listeners, which commit on their own threads.
4Rule 3: Reference Data Comes From Migrations and Is Read-Only
Some data every test needs: countries, currencies, product categories, permission names. That data should be inserted by the Flyway or Liquibase migrations, exactly as in production, so it exists before any test starts. Tests may read it but never change it. If a test needs a special category, it creates a new one with a unique name rather than modifying a shared one, because changing shared data in one test is a collision with every test that reads it.
5Rule 4: Assert on Your Own Rows, Not on the Table
The most common hidden assumption is in the assertions. A check such as 'the orders table now has one row' only holds if nobody else is writing to the table. The fix is to scope every assertion by the test's own ids, as we did with findByTenant(tenant). The same applies to aggregate checks.
Endpoints that list data need the same care. If an API test calls GET /orders and expects a list of two, it should filter by its tenant or customer, or check that the list contains its two orders rather than that it has exactly two entries.
6When a Test Needs the Whole Database: Per-Test Schemas
A few tests genuinely need a database that nobody else touches: a report that aggregates across all tenants, a batch job that processes every unprocessed row, or a test of a migration itself. For those, the shared container can still be used, with a fresh schema per test class. The test creates a schema with a random name, runs the migrations into it, and points its data source at it with a search path setting.
| Option | Isolation | Cost | Use for |
|---|---|---|---|
| Unique ids per test | Logical, by filtering | Almost none | Most tests |
| Rollback on test thread | Full, uncommitted rows | None | Repository and slice tests |
| Delete own rows after test | Leaves no trace | Small | Tests that create a lot |
| Schema per test class | Full, physical | A migration run per class | Cross-tenant reports, batch jobs |
| Separate sequential phase | Full, by time | Longer total run | The few global tests |
This costs a migration run per class, typically a second or two for a moderate schema, so it should be the exception. Another simple option is to tag these tests and run them in a separate, sequential phase after the parallel ones. The combined design gives us the speed of one shared container with the isolation of separate databases where it is really needed.
7Follow-up questions
Why not give every test its own container?
Because start-up time would dominate. A PostgreSQL container plus migrations takes several seconds, so 300 test classes would add many minutes. One shared container, with isolation by data, costs a few seconds once. Per-class containers make sense only for the rare tests that need different database settings.
How do you stop new tests from breaking the rules?
Make the rules easy to follow and hard to break. The shared test library offers the unique id helpers and tenant-scoped builders, a simple check in code review or an ArchUnit rule can flag TRUNCATE and unscoped count() calls in test code, and running the suite in parallel on every build means a test that relies on being alone fails quickly and visibly.
What about sequences and generated ids that tests assert on?
Tests should never assert on specific generated values such as 'the first order has id 1', because in a shared database other tests consume the same sequence. Assert on the id returned from the save or the API response instead.
8Conclusion
In this answer, we designed test data for parallel tests on one shared container. Each test creates its own data with unique identifiers, ideally a tenant of its own, and every assertion filters by those ids instead of counting whole tables. Global cleanup is removed; tests delete only their own rows or leave them for the throwaway container. Reference data comes from migrations and is read-only, and the few tests that need the whole database get their own schema or run in a separate sequential phase.
Open with
My starting principle is that isolation comes from the data, not from timing. Every test creates the data it needs and makes it unique: random suffixes on emails and order numbers, and in a multi-tenant system a fresh tenant per test, since most queries already filter by tenant.
Then, if they want more
That removes unique constraint collisions. Second, no global cleanup. TRUNCATE or delete-all in one test destroys another test's data mid-run, so a test either deletes only its own rows by id, or doesn't clean up at all, because the container is thrown away after the run anyway, and leftover rows help debugging.
Tests that run fully on the test thread can still use rollback. Third, reference data like countries and currencies is loaded once by the Flyway migrations, the same as production, and treated as read-only; if a test needs a special category, it creates its own.
Fourth, assertions are scoped: never assert the table has one row, assert this tenant has one order, and never assert specific generated ids.
Finally, for the few tests that really need the whole database, like a cross-tenant report or a batch job, I either give that test class its own schema with migrations applied, or run those tests in a separate sequential phase. I'd enable JUnit parallel execution per class first and let the shared test library provide the id helpers.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- JUnit 5
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JUnit user guide, Mockito documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design a test data strategy for integration tests that run in parallel against one...": https://scrivio-interview-library.netlify.app/java/integration-testing/c484f541c3/