Mocks vs Real Dependencies: Backend Tests
- Average speed
- km/h
- Result
- Finish time
- 50 min
- You entered
- Distance
- 10 km
- You entered
Backend tests should use real dependencies by default, and mocks only when a real dependency is unavailable, too slow, or nondeterministic. This rule keeps tests honest: they verify the actual integration points of your code, not a programmer’s guess about how those points behave. The rest of this article explains the trade-offs, when to break the rule, and how to structure tests to get the best of both worlds.
Formula
This calculator works out your average running pace and speed from a finish time and distance. Enter the total time in minutes and the distance in kilometers, and it returns your pace in minutes per kilometer and your speed in kilometers per hour. The formulas are:
- Pace (min/km) = Finish time (min) ÷ Distance (km)
- Speed (km/h) = Distance (km) ÷ (Finish time (min) ÷ 60)
Where:
- t = finish time in minutes
- d = distance in kilometers
- pace = minutes per kilometer (lower is faster)
- speed = kilometers per hour (higher is faster)
Worked Example
Using the default values from the calculator: you finish a 10 km run in 50 minutes.
- Pace = 50 min ÷ 10 km = 5.00 min/km
- Speed = 10 km ÷ (50 min ÷ 60) = 10 km ÷ 0.8333 h = 12.00 km/h
The calculator shows a pace of 5.00 min/km and a speed of 12.00 km/h, matching the steps above.
Why Real Dependencies Usually Win
The main reason to prefer real dependencies is that they catch integration errors that mocks cannot. A mock verifies that your code calls a method with certain arguments; a real dependency verifies that those arguments actually work. For example, if you mock a database repository, your test will pass even if your SQL query has a syntax error. With a real test database, that error surfaces immediately.
Real dependencies also protect against “drift” between your mocks and the actual library or service. Libraries change their behavior, add required parameters, or alter error formats. Your mock still returns the old response, so your tests stay green while production breaks. Real dependencies keep your tests tied to reality.
Finally, real dependencies give you confidence in the whole stack. A test that writes to a real PostgreSQL database and reads it back proves your code works end-to-end, not just in isolation. That is the kind of test that catches subtle bugs like transaction handling, connection pooling, or serialization issues.
When Mocks Are the Right Choice
There are legitimate reasons to mock, and knowing them prevents dogmatism. Use mocks when:
- The dependency is unavailable in the test environment – e.g., a third-party SaaS API that requires credentials or a paid plan.
- The dependency is too slow – e.g., a machine-learning model that takes minutes to run.
- The dependency is nondeterministic – e.g., a random number generator or the current time; you need to control the output to test specific branches.
- The dependency has side effects you don’t want in tests – e.g., sending emails or charging credit cards.
- You are testing error handling – e.g., simulating a timeout or a 500 response from a service.
In these cases, mock the dependency at its boundary (the interface or client class), not deep inside your code. This keeps your test focused on your logic while still letting you control the external behavior.
How to Choose: A Decision Framework
When deciding for a specific test, ask these questions in order:
- Can I use the real dependency quickly and safely? If yes, use it. This includes local databases, in-memory caches, and test instances of your own services.
- Is the real dependency fast enough? If it takes more than a few seconds per test, consider mocking or using a lighter substitute (e.g., SQLite instead of PostgreSQL for simple queries).
- Is the real dependency deterministic? If it returns random data or depends on wall-clock time, mock the specific part that is nondeterministic, but still test the rest with real calls.
- Is the dependency a third-party service? If so, mock it unless you have a sandbox environment that is reliable and free. Even then, run a small subset of tests against the real service in CI.
- What are you actually testing? If it’s your business logic, mocks are fine. If it’s the integration between your code and the dependency, you need the real thing.
This framework leads to a pragmatic mix: most unit tests use mocks for external services, but integration tests use real databases, message queues, and HTTP servers.
Common Problems and Misconceptions
A frequent misconception is that mocks are “fake” and therefore always bad. In reality, mocks are a tool – the problem is overusing them. When every test mocks everything, you end up testing the mock, not your code. This gives false confidence.
Another common issue is mocking classes instead of interfaces. If you mock a concrete class, your test is tightly coupled to its implementation details. If the class changes internally, your mock breaks even though your code still works. Mocking an interface or a thin client class avoids this.
People also often mock too much in a single test. If you mock five dependencies, you’re testing how your code coordinates those mocks, not how it works with real systems. Keep mocks minimal – only mock what is necessary for the test’s purpose.
Finally, many teams skip integration tests entirely because they are “hard to set up.” But modern tools make this easier: Docker Compose can spin up a database, Testcontainers can manage ephemeral instances, and H2 or SQLite can substitute for many relational databases. The setup cost is worth it because integration tests catch the bugs that matter most.
Costs and Trade-offs
Real dependencies come with costs. They are slower, require more setup, and can be flaky if not managed well. A test suite that hits a live database can take minutes instead of seconds, which slows down development. Flaky tests – ones that pass sometimes and fail randomly – erode trust and waste time.
Mocks are fast and stable, but they carry a hidden cost: maintenance. As your code evolves, you must update mocks to match new interfaces and behaviors. If you mock too much, you spend more time fixing tests than writing features.
The key is to balance speed and realism. A common strategy is the “test pyramid”: many fast unit tests with mocks, fewer integration tests with real dependencies, and even fewer end-to-end tests. This gives you speed where you need it and confidence where it matters.
Alternatives to Mocks
Before reaching for a mocking library, consider these alternatives:
- Test doubles that are not mocks – stubs return fixed data, fakes have working implementations (e.g., an in-memory repository), and spies record calls. These are often simpler and more realistic than mocks.
- Dependency injection – design your code to accept dependencies via constructors or setters, making it easy to swap real implementations for test doubles.
- Contract testing – instead of mocking a third-party API, use a contract test that verifies your code and the real API agree on request/response formats. This catches drift without needing the real service in every test.
- Testcontainers or Docker – spin up real databases, message brokers, or other services in isolated containers for integration tests. This gives you real dependencies without polluting your local environment.
- In-memory implementations – for example, use SQLite for tests when your production uses PostgreSQL, as long as you stick to common SQL features. This is faster than a real PostgreSQL instance but still tests real SQL syntax.
Each alternative has its own trade-offs, but they all aim to bring your tests closer to production reality without the full cost of a live system.
Frequently Asked Questions
Should I mock my own database repository?
No, unless you are unit-testing a service that uses the repository and you want to isolate its logic. For testing the repository itself, use a real database. If you mock your own repository, you are not testing the SQL or the mapping code – you are only testing that your service calls the repository correctly.
How do I mock time-dependent code?
Inject a clock or use a library like freezegun (Python) or Mockito’s `mockStatic` (Java) to control the current time. This is a legitimate use of mocks because time is inherently nondeterministic. But be sure to also write a few tests with real time to catch issues like timezone handling.
What is the difference between a mock and a stub?
A stub returns predefined data and does not verify behavior; a mock also verifies that certain methods were called with expected arguments. In practice, many developers use “mock” loosely to mean any test double. For clarity, use stubs when you just need data, and mocks when you need to assert interactions.
Can I use mocks in integration tests?
Yes, but only for parts that are genuinely external or nondeterministic. For example, in an integration test that hits a real database, you might mock the email service to avoid sending actual emails. The key is to mock only what is not the focus of the test.
How do I prevent flaky tests with real dependencies?
Use isolated test databases (e.g., a fresh schema per test), run tests in a clean environment, and avoid shared state. Use retries for network calls only if the service is known to be flaky, but prefer fixing the root cause. Finally, run integration tests in CI but not on every commit – schedule them nightly or on merge to main.
Is it okay to mock a third-party API in unit tests?
Yes, especially if the API requires authentication or has rate limits. But also create a few integration tests that hit the real API (or a sandbox) to verify your request format and response parsing. This combination catches both logic errors and API changes.
Related
Formula used
in t | Finish time | min | 50 | 0 in d | Distance | km | 10 | 0 out pace | Average pace | min/km | t / d | 2 out speed | Average speed | km/h | d / (t / 60) | 2
Each line is one input (in, sel, list) or one result (out: label, unit, formula, decimals). How the calculators work
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.