Testing Backend Services with Real Dependencies
Test databases, fixtures, resetting state between tests, ephemeral containers versus mocking, and stubbing external HTTP dependencies.
Testing Backend Services with Real Dependencies
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- A unit test with every dependency mocked proves your code calls the methods you expected it to call — it doesn't prove a real database would accept that query, enforce that constraint, or return rows in the shape you assumed.
- Testcontainers-style tooling starts a real instance of a dependency — Postgres, Redis, a message broker — in a disposable Docker container for the duration of a test run, then tears it down, giving you real behavior without a shared, stateful test environment.
- Tests that touch a real database need explicit, deliberate state management between runs — fixtures or seed data to start from a known state, and a reset step (truncate, transaction rollback, or a fresh container) so one test's leftover data can't change another test's result.
- External third-party HTTP dependencies should be stubbed, not hit for real, in a test suite — a tool like WireMock runs a fake HTTP server your code talks to over a real network call, so tests stay fast and don't fail when a vendor's API is slow or down.
What a mock can’t tell you
By the time you’re writing tests for a backend service, you’ve probably already internalized the standard advice: isolate the unit under test, mock its dependencies, keep tests fast. That advice is correct for pure logic — a function that calculates a discount, validates a shape, transforms one data structure into another. It starts failing you the moment the code you’re testing is a repository method, a query, or a client that talks to an external service, because a mock of a database only knows what you told it to know.
Here’s the gap concretely: you write a repository method that runs a query joining two tables with a WHERE clause on a timestamp column. You mock the database call in your test, have the mock return a canned list of rows, and assert your code processes that list correctly. The test passes. It tells you nothing about whether the actual SQL is valid, whether the join produces the rows you think it does, whether a unique constraint you’re relying on actually exists in the schema, or whether a timezone mismatch between your app and the database silently drops rows at the boundary. A mock test proves your code calls the right methods — it doesn’t prove the right things happen in the database itself. This is specifically about testing your code’s interaction with a real-ish dependency; the general shape of unit versus integration versus end-to-end tests that this lesson assumes is covered in Testing Fundamentals.
Test databases, fixtures, and seed data
The traditional fix predates containers: stand up a dedicated test database, separate from production, and run your test suite against it. That solves the “don’t test against prod” problem but introduces a new one — a test database needs to start from a known state for a test’s assertions to mean anything. If a test checks “a new user signup creates exactly one row,” that only works if the table was empty (or at a known count) before the test ran.
This is what fixtures and seed data are for: a defined, version-controlled set of starting rows — a few sample users, a known product catalog, whatever baseline state your tests are written against — loaded before a test run begins. Fixtures turn “the database is in some state” into “the database is in this specific state,” which is the only way assertions about row counts, specific values, or query results can be reliable.
Resetting state between tests
Seeding a known starting state solves half the problem. The other half is what happens during a test run: tests create, update, and delete rows, and if that leftover state bleeds into the next test, your suite becomes order-dependent and flaky — a test that passes alone can fail only when run after another specific test, which is one of the worst categories of bug to chase down. A few standard resets:
- Wrap each test in a transaction and roll it back at the end, so every write the test made simply vanishes, regardless of what it did.
- Truncate the relevant tables between tests or between test files, re-seeding fixtures fresh each time.
- Start a brand-new container per test run (or per test suite), so there’s no leftover state by construction — the tradeoff is startup cost, which is why this is usually done per-suite rather than per-test.
None of these is universally correct; the right choice depends on how expensive starting a fresh dependency is versus how expensive a transaction wrapper is in your stack, and how much true isolation a given test actually needs.
Testcontainers: a real dependency, disposable
The real shift the Testcontainers pattern introduces is treating “spin up a real instance of a dependency” as part of the test’s own lifecycle rather than a separately managed, long-lived environment. A test suite that needs Postgres starts an actual Postgres instance in a Docker container when the suite begins, hands your code a real connection string, and tears the container down when the suite finishes — no shared test server anyone has to maintain, no state one CI run leaves behind for the next one to trip over. The embedded video above walks through exactly this for a Spring Boot service: a repository test and a controller test both run against a real Postgres container rather than a mock, and the win is direct — the test now exercises your actual SQL against an actual database engine, catching the class of bug a mocked repository can never catch, while staying fully disposable and reproducible on any machine with Docker installed, including CI.
This pattern isn’t Java-specific — equivalent libraries exist for Go, Python, Node.js, .NET, and Rust, and the idea generalizes past databases to any dependency you’d otherwise mock: a real Redis instance, a real Kafka broker, a real message queue. The tradeoff against pure mocking is honest: a container takes real seconds to start and the test needs Docker available, so these tests are slower than pure unit tests and usually live in a separate integration-test suite rather than running on every keystroke. That’s a reasonable price for catching bugs a mock structurally cannot catch.
Mocking the dependencies you don’t own
Testcontainers solves “I need a real database for this test” — it doesn’t solve “I need to call a third-party payment processor’s API during this test.” For dependencies outside your own infrastructure, the right move flips: don’t call the real thing. A real external API can be slow, rate-limited, flaky, or billed per call, and none of that should be able to make your own test suite unreliable. A tool like WireMock runs an actual local HTTP server that your code talks to over a genuine network call — so you’re still exercising your real HTTP client code, timeout handling, and response parsing — but the responses are stubs you define: a successful payload, a 500, a slow response to test your timeout logic, a malformed body to test your error handling. This is deliberately distinct from the API-contract-level testing covered in Contract Testing for APIs and Mocking and Virtualizing APIs — those are about verifying your API’s own contract with its consumers; this is about neutralizing a dependency you call, so your tests only fail when your own code has a real bug.
Check yourself
What's the specific limitation of a test that mocks the database layer entirely?
A mock only confirms that your code called the mocked method with the arguments you expected — it says nothing about whether a real database would accept that SQL, enforce a unique constraint the way you assumed, handle a transaction isolation edge case correctly, or serialize a value the way your code expects. Mocks test that your code calls the right methods, not that the right things happen in the actual database.
What problem does a tool like Testcontainers solve that a shared, always-on test database doesn't?
A shared test database accumulates state across test runs and across developers, so one test's leftover row can silently break another test weeks later, and two CI jobs running at once can stomp on each other's data. Testcontainers starts a fresh, real instance of the dependency — isolated, disposable, torn down after the run — so every test run starts from the same known state with no cross-contamination.
Why isn't it enough to just seed a test database once and leave the data there for every test to reuse?
Tests need to start from a known state to be reliable, and a database that accumulates whatever the last ten test runs left behind isn't a known state. Without an explicit reset — truncating tables, rolling back a wrapping transaction, or spinning up a fresh container per run — a test that passed yesterday can fail today because an earlier test in the same run mutated a row it depended on.
When should you reach for Testcontainers versus a plain mock in a given test?
Use a real, containerized dependency when the thing you're actually testing is the interaction with that dependency itself — a specific query, a migration, a constraint, a cache eviction policy. Use a mock when the dependency is incidental and you're really testing pure business logic that happens to call a repository or client along the way; spinning up a container to test logic that doesn't actually touch the database is paying integration-test cost for a unit-test question.
Why shouldn't a test suite make real HTTP calls to an actual third-party API?
A real external API can be slow, rate-limited, temporarily down, or cost money per call, and none of those should be able to make your own test suite fail or go red. Stubbing the HTTP layer with a tool like WireMock gives you a fake server that returns whatever response you tell it to — success, a 500, a timeout — so you can test how your code handles each case deterministically, without depending on a third party's uptime.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.