How do you keep database integration tests isolated, repeatable and safe?
Answer
Give each test controlled data and ownership through a transaction, unique tenant or schema, deterministic fixture or disposable database, depending on what the test must observe. Clean up reliably, but do not hide commit, trigger, locking or cross-transaction behaviour by wrapping every test in a rollback that production never uses. Parallel runs need collision-proof identifiers, bounded permissions, no production credentials, representative constraints and diagnostics that identify the created records when cleanup fails.
Strong answer includes
- selects isolation that preserves the behaviour under test
- handles parallel data collisions and cleanup
- uses least privilege and never production credentials
Practical example
Runs against the resettable SQLite sample database used by the playground.
Run the query to see the result.
The test owns a unique row and rolls it back after assertions. This pattern is useful when the behavior under test does not require observing a committed transaction from another connection; otherwise a disposable schema/database or explicit cleanup may be more faithful.
Expected result: The final count is zero after rollback.