Testing Strategy

Problem / Context

Bugs slip past mocked database layers because SQL, constraints, and triggers are not exercised. You want fast, reliable tests that use a real Postgres instance, isolate data per test run, and avoid flaky assertions.

Pyramid

  1. Unit (pure logic / SQL fragments)
  2. Integration (real DB)
  3. Contract / API

Core Concept

Implementation (Step by Step SQL)

Real DB over Mocks

Test DB Lifecycle

Parallelism

Data Isolation Options

Technique Pros Cons
Transaction Rollback Fast No cross-conn coverage
Truncate Tables Cross-conn Slower, need FK defers
Template DB Clone Near-instant Requires superuser

Determinism

Flaky Sources

Assertions

Prefer structural over incidental:

Tooling

Variations and Trade‑Offs

Pitfalls

Recap (Short Summary)

Use a real DB, isolate state per test, keep data setup minimal and explicit, and make time/random deterministic to avoid flakes.

Optional Exercises

Summary (Cheat Sheet)

Principle: Aim for high signal and low brittleness to build trust in failures.

References