0%
Test Doubles with Mockito

Mockito Test Doubles

Mock, spy, interaction verification, and the test that tests itself.

10-15 min

Test Doubles with Mockito

Here is a test that passes, counts toward coverage, and detects absolutely nothing:

@Test
void le_service_retourne_le_client() {
    when(depot.parId(7L)).thenReturn(new Client(7L, "Dupont"));

    Client client = service.trouver(7L);

    assertThat(client.nom()).isEqualTo("Dupont");
}

You declared that the repository returns "Dupont", then verified that "Dupont" comes out. The only behavior being tested is Mockito's. Replace the implementation of service.trouver with return depot.parId(id);, deleting all the business logic it contained, and the test stays green. This is the most common flaw in suites that overuse test doubles, and the coverage counter can't detect it: it will proudly display 100% on the method.

Mockito is an excellent tool that is misused by default. The reflex of "one class under test, every collaborator mocked" produces tests that describe the internal structure of the code instead of its behavior: every time a responsibility moves between two classes, ten tests break even though no bug was introduced. This lesson lays out a simple rule for deciding when a test double is justified, and shows how to verify interactions without painting yourself into a corner.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!