Video in progress

The unit tests written for domain code each need 6–8 mocks. What does that say about the design, and how do you change the testing strategy?

This is usually a design signal: the class is tied to too many collaborators, the logic is scattered across services, and the domain objects are anemic. I move the logic into pure domain objects and test them without mocks, and cover the external boundaries with a small number of integration tests.

📖 Answer

Lots of mocks does three kinds of damage:

  • tests stick to the implementation: verify(repo).save(...): if you refactor, the tests break even when the behavior is the same;
  • mocks can lie: the real repository behaves differently and the test stays green;
  • you can't read the test and understand the business rule.

Fixing it on the design side:

  1. Separate the decision from I/O ("functional core, imperative shell"). The service loads data, a pure domain object makes the decision, and the service saves the result.
// the decision: pure, no mocks needed
LoanDecision decision = LoanPolicy.evaluate(applicant, history, limits);

// test
assertThat(LoanPolicy.evaluate(applicantWithDebt(), cleanHistory(), defaultLimits()))
    .isEqualTo(LoanDecision.rejected("DEBT_RATIO"));
  1. Group the collaborators. If 4 of the 8 dependencies are always used together, they're one concept: extract them into a separate class.
  2. Make time and randomness a parameter: Clock, an ID generator: plain fakes, not mocks.

The testing strategy:

  • Domain: many fast unit tests, no mocks.
  • Application service: with an in-memory fake repository (a plain HashMap), not a mock.
  • Adapters: integration tests against a real PostgreSQL/Kafka with Testcontainers: few, but real.
  • Mocks only at boundaries that aren't yours and where a fake is hard to write (external HTTP: WireMock).

A simple metric: the number of verify( calls in tests shouldn't grow. You can watch it with a plain grep, and it shows which direction the design is heading.