Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Patterns and Pitfalls

Over-Mocking and Test Smells

Spot the signs of over-mocked tests: brittle interaction checks, mocked value objects, mocks of the class under test. Learn what to mock, what to keep real, and how to refactor.

Mockito makes it so easy to replace a dependency that it is tempting to replace all of them. The result is a test suite that is green but useless: it passes when the code is broken and fails when the code is merely refactored. This lesson names the common smells, shows two of them running, and gives a practical rule for deciding what deserves a mock.

Mockito is not available on this site; real Mockito snippets are read-only. The runnable parts use plain Java and the labelled Mini stand-in.

What is worth mocking?

A good question to ask for every collaborator: does it cross a boundary?

Mock or fake it Keep it real
Databases, HTTP clients, message brokers Value objects (Money, Email, records)
The clock, randomness, file system Pure functions and small helpers
Slow or nondeterministic services Collections, strings, DTOs
Systems with side effects you must not trigger Your own simple domain objects

Mocks are for boundaries and side effects. Everything inside the boundary should just run.

Smell 1: verifying the implementation, not the behavior

Java
@Test
void importsUsers() {
    service.importAll(file);

    InOrder inOrder = inOrder(parser, validator, repo);
    inOrder.verify(parser).parse(file);
    inOrder.verify(validator).validate(any());
    inOrder.verify(repo).save(any());
    verifyNoMoreInteractions(parser, validator, repo);
}

This test is a transcript of the code. Rename a method, merge two calls or add a log line and it fails, although the program still works. It documents how, not what.

Compare the same behavior stated as an outcome: "after importing a valid file the three users are stored". With a fake repository you assert on its contents and the test survives refactoring.

Java Interaction test breaks on a harmless refactor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The interaction test (counting save("ana") calls) happened to encode an accident of version 1. The outcome check on the fake still passes after the refactor.

Smell 2: mocking value objects and data

Java
Order order = mock(Order.class);
when(order.total()).thenReturn(new BigDecimal("50"));
when(order.items()).thenReturn(List.of());

If Order is a simple data class, build it: new Order(List.of(item("book", 50))). A mock of a value object duplicates its logic in the test and breaks as soon as a method you did not stub gets called by the code under test. Rule: if the class has no side effects and no outside dependency, use the real one.

Smell 3: a mock for every collaborator, ten of them

A test needing ten @Mock fields is a message about the design. The class under test does too much. Splitting it makes each test need two or three mocks.

Smell 4: mocking the class under test

Java
Service service = spy(new Service(repo));
doReturn(5).when(service).helper();      // now you test your stub

If you must stub a method of the class under test, that method belongs in another class (see Partial mocks).

Smell 5: unnecessary verifyNoMoreInteractions

verifyNoMoreInteractions is a way to say "nothing else happened". Useful sparingly (for example, a decline must not touch the order store). Used on every test it freezes the implementation, like smell 1.

Smell 6: mock-returns-mock chains

when(a.getB().getC().getValue()): the test knows the whole object graph. See Deep stubs and the Law of Demeter.

Smell 7: tests that only prove wiring

Java
@Test
void callsRepo() {
    service.find(1);
    verify(repo).findById(1);
}

If the method returns what the repo returned, assert the result (assertEquals(user, service.find(1))) with the stub. The verify adds nothing, except a failure when you rename the repo method.

What to verify then?

Verify side effects that leave the system, where the only visible evidence is the call itself:

  • an email was sent;
  • a payment was requested with the right amount;
  • an event was published;
  • nothing was written when validation failed.

For everything else, assert on returned values and on the state of fakes.

A decision guide

flowchart TD
  A["Collaborator in my class"] --> B{"Crosses a boundary or has side effects?"}
  B -->|"No"| C["Use the real object"]
  B -->|"Yes"| D{"Do I need to assert on calls made to it?"}
  D -->|"Yes, outgoing effect"| E["Mock + verify"]
  D -->|"No, it only supplies data"| F["Stub it, or use a fake"]

Real by default; mock at boundaries; verify only outgoing effects.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. A test verifies the exact sequence of calls on three mocks plus verifyNoMoreInteractions. What is the main risk?

    Such a test describes the implementation. Harmless changes like merging calls break it.
  2. 2. Which type should normally NOT be mocked?

    Value objects are cheap and deterministic. Create real instances instead.
  3. 3. A test needs ten @Mock fields. What does this most likely indicate?

    Many dependencies are a design smell; splitting the class reduces mock count per test.

Summary

  • Mock boundaries and side effects; use real objects for values and pure logic.
  • Verify outgoing effects, not every internal call; assert results and fake state otherwise.
  • Many mocks, mock chains, spied subjects and blanket verifyNoMoreInteractions are smells pointing at design or test style.
  • Refactoring should not break tests that describe behavior.

Next: Deep stubs and the Law of Demeter