To mock or not to mock November 24, 2026
I'm writing this because I have seen a lot of testing code that used some mocking library to mock[1] way too many dependencies in unit tests. The thinking seems to go like this: A unit test is supposed to test a single class only, so anything that this class depends on must not influence the test, so let's mock everything that is passed into the class by our dependency injection framework. This is a bad idea.
Every mock is an assumption. Actually, two. First, if you mock the behaviour of a dependency in a test, you assume that this behaviour is relevant to the behaviour that you are testing. This may not be true. And if it is true now, it may not stay so in the future. For example, I often see verifications like these in error-handling tests (pseudocode):
action_should_not_change_customer_on_invalid_input() {
repository = mock(CustomerRepository)
service = new CustomerService(repository)
service.do_action(invalid_input)
verify(repository.update(any()))
.has_not_been_called()
}
The purpose seems to be to verify that customer data is not updated when invalid
input is provided. This sounds reasonable at first glance, but think about this:
If CustomerRepository has a different update method, its invocation might not
be detected by this code (depending on how strict your mocking library is). And
if the implementation of CustomerService is later changed to always perform
updates but roll them back on error (which is a completely reasonable
implementation choice), this test will break, and it will break unnecessarily
because what really matters for this test is whether customer data remains
unchanged, not whether update() has been called.
A better test would check directly that the customer has not been changed:
action_should_not_change_customer_on_invalid_input() {
repository = new CustomerRepository(data_source)
repository.insert(existing_customer)
service = new CustomerService(repository)
service.do_action(invalid_input)
assert_that(repository.find(existing_customer.id))
.is_equal_to(existing_customer)
}
Another example is a test I recently wrote myself for a new method on an HTTP controller. I added it to the existing test class. At first, it looked something like this:
post_should_return_a_valid_response_for_valid_input() {
when(some_service.act(valid_request))
.then_return(valid_result)
response = post(url, valid_request)
assert_that(response.body()).is_json("{…}")
}
some_service is a dependency of the controller method responsible for the
actual action. It is mocked because this is not an integration test but a test
for the controller only. The mocks are set up in a base class from which the
controller test class is derived. Unfortunately, the test didn't work. It
always returned an empty response body. It took me over an hour to find my
mistake. The implementation of the controller method looks something like this:
do_something(request) {
return mapper.to_dto(some_service.act(request))
}
Do you see it? There's a mapper that transforms the result of the action into a
data transfer object. And … the mapper is mocked in the test, which I hadn't seen
because it is done in the base class. And because the mocking framework just
returns null if no result has been prepared, it actually does not matter at
all what some_service.act() returns. I had to stub the mocked mapper to make it work:
post_should_return_a_valid_response_for_valid_input() {
when(some_service.act(valid_request))
.then_return(valid_result)
when(mapper.to_dto(valid_result))
.then_return(valid_dto)
response = post(url, valid_request)
assert_that(response.body()).is_json("{…}")
}
But now, what does the test actually test? Basically only the web framework. And it now encodes the dependency on the mapper. Does it really matter to the test that the mapping is done by a separate class? Should the test break if I choose to inline the mapping?
The second assumption is that the behaviour is mocked correctly.
I once investigated a bug in the HTTP API of a payment service.
If a duplicate transaction was submitted, it would return an internal server
error (HTTP status code 500), even though the code contained an explicit error
handler for this case that was supposed to respond with HTTP status code 409.
Code coverage for this code path was at 100%. The database adapter contained a
test checking that a DuplicatePaymentException was thrown when the unique
constraint was violated during insertion into the database. And there was a test
at the API layer that ensured that in case of a
DuplicatePaymentTransactionException the correct response was sent to the
client. You see? The mock database adapter in the latter test did indeed throw a
DuplicatePaymentTransactionException. The real adapter threw a
DuplicatePaymentException (almost, but not quite, the same) instead, which
bypassed the explicit error handler
and was propagated to the global fallback error handler, which turned it into
HTTP status code 500. All tests passed, yet the aggregate behaviour was still
incorrect.
So, every decision to mock a behaviour in a test encodes these two assumptions:
that the behaviour is relevant and that it is mocked correctly.
As we have seen, each of these two assumptions can be wrong. But even if they
are correct at the time the test is written, they may become wrong over time.
Suppose that in the above example, the request for the controller gets a new
mandatory attribute, and the validation is part of some_service.act().
This would cause all requests missing this attribute to fail. But do we see this
in our test? No, we don't! Because the statement
when(some_service.act(valid_request))
.then_return(valid_result)
isolates our test from the actual behaviour of some_service.act(). If what
was previously a valid request becomes invalid because we did not add the
mandatory attribute to it, the test will still pass because it assumes the old
behaviour. The test has become misleading at best, and a contributor to a
production incident at worst.
Now, I do think mocks – or rather, different kinds of test doubles – can improve tests if used strategically. And that means sparingly. So when should you use them and when shouldn't you?
Heuristics
Use stubs for determinism. Non-deterministic behaviour is an endless source of “fun” in tests. One source of non-determinism I have encountered particularly often is time. Code that depends on the current time shouldn't usually determine the current time by itself but use a clock injected via dependency injection. This makes it easy to “manipulate time” for testing purposes and makes the tests much more reliable. The same applies to other sources of non-determinism (random number generators, …).
Use stubs or fakes for reliability. If a test depends on an external system with less than 100% reliability (basically all external systems, but especially those connected over a network), the test will fail sporadically, causing much wailing and gnashing of teeth. If you can improve the reliability of the external system without resorting to fakes, e.g., by launching a real database for the test locally instead of accessing it over the network, this is preferable to using a different database implementation for testing purposes. But if for some reason you can't, you must resort to a fake or a stub.
Use stubs for difficult error conditions. Sometimes, you want to test how your code handles errors that should be impossible to generate in production (defensive programming) or that would be difficult to create for real (such as failing hardware). In these cases, you might not have better options than to resort to stubs that throw exceptions or the like. Keep in mind, however, that the stub encodes an assumption about the way the error will manifest, and that this assumption might or might not be correct.
Use fakes for missing implementations. Sometimes, you may want to test code that depends on an interface, and no implementation of that interface exists in your project. You might be developing a library that provides an interface and expects the caller to supply an implementation, for example. If there is no “real” implementation, obviously, the tests will have to provide a fake one.
Don't mock internal structures. A unit test should depend only on the externally visible properties of the unit under test.[2] Implementation details should be hidden and you should be able to change them without having to change the test. Importantly, the internal decomposition of the unit under test is an implementation detail! While it is OK to extract part of the implementation to a helper class such as the data mapper in the example above, it is not OK to have the test depend on it (by encoding its assumed behaviour in a mock).
Don't mock single-use dependencies. I often see code where a controller class calls a service class with some business logic, which in turn calls another service class that implements part of the logic. Often, the first service is the only caller of the second service. Even though this might look like a valid use case for mocking because both classes have “service” in their names and are located at the same level in the package hierarchy, it's really only a special case of the previous heuristic. The naming obscures the fact that you have distributed a functional unit (in the business sense) across multiple classes.
Don't mock data objects. Behaviour verification for data objects is nonsensical. Granted, construction of a complex data object might require a lot of boilerplate code, and if you only need a small part of it, using a mocking library to stub some getters might look attractive, but it's really better to write a factory method instead. This way, you get a real data object, and if one day someone adds validation to it, the test will include it instead of relying on an outdated assumption about what constitutes a valid object.
Don't verify intermediate interactions. There may be some interactions between the unit under test and external systems that are relevant and can more reliably be tested with a fake (e.g., verifying that an email has been sent is a good use case for a fake mail server). Still, I find that most interactions between a unit under test and other classes or systems contribute to the end result, but are not that relevant by themselves. For example, updating a record in a database may require reading and writing multiple tables in sequence, but I wouldn't recommend encoding this sequence in a test. I'd much rather check the end result because this makes the test much more robust.
Only mock stable interfaces. Because every mock is an assumption about the behaviour of the mocked thing, frequently breaking these assumptions leads to a lot of work (you need to adjust all tests containing these assumptions) or a lot of wrong tests (if you don't bother or forget to adjust all the tests). The risk of this happening is much lower if the interface (including its semantics) is stable. Ironically, this means that it is pretty safe to mock a string class provided by your programming language's standard library (which practically no one does) because its interface is very unlikely to change and thus break your assumptions, but it is rather unsafe to mock your own helper classes that don't have a properly specified interface (which I have seen done very often) because those are much more likely to change and thus break your tests.
That's it. These are my heuristics. Taken together, they allow me to write tests that rely on mocking (or “test doubling”) only when there is a real benefit, and that don't encode too many assumptions. Mostly, the tests I get to see in the line of my work use too much mocking. Your experience might differ, but in any case, the next time you reach for your mocking library you might want to ask yourself what assumptions you are encoding into your tests – and if they really belong there.
Footnotes
I'm using the term loosely here, sorry. ↩︎
And the unit under test does not have to be a single class. For more on this, see my post Unit testing vs. integration testing. ↩︎