Video in progress

Strong Middle 🧪 Testing

What problems does too much mocking in tests (over-mocking) lead to, and where do you draw the line?

If every dependency is mocked, the test just replays the code's internal sequence of calls: on refactoring the test breaks even when behavior hasn't changed, and real integration bugs stay invisible. I mock only things at the boundary: network, time, external APIs.

📖 Answer

What over-mocking typically looks like:

when(mapper.toEntity(dto)).thenReturn(entity);
when(validator.validate(entity)).thenReturn(List.of());
when(repo.save(entity)).thenReturn(saved);
when(mapper.toDto(saved)).thenReturn(resultDto);

var result = service.create(dto);

assertSame(resultDto, result);
verify(mapper).toEntity(dto);
verify(validator).validate(entity);
verify(repo).save(entity);

What does this test prove? Only that "the method calls these four methods in this order". If the mapper drops email, the test is still green. Tomorrow you move the validation into the entity, and the test goes red even though nothing is broken.

The lines I draw:

  • plain classes in our own code with no side effects (mapper, validator, value object): the real one is used;
  • the repository: a fake (in-memory) or an integration test with Testcontainers;
  • anything that leaves the process (HTTP client, message broker, Clock, email): a mock or stub;
  • the "don't mock types you don't own" rule: instead of mocking RestTemplate or KafkaTemplate directly, write your own adapter on top and mock that.

As a sign: if the test has more stubs than asserts, or you have to rewrite the test on every change, that's over-mocking.