Video in progress
When Mockito throws UnnecessaryStubbingException, what does that mean, and what's the right fix?
MockitoExtension runs in strict stubs mode by default: if the test stubs a method that is never called, the test fails. This usually points to a redundant stub, or one written with the wrong argument.
📖 Answer
An example:
when(repo.findByEmail("ali@mail.uz")).thenReturn(Optional.of(user));
service.login("Ali@mail.uz", "parol"); // the code passed the email in a different form
The stub didn't fire because the argument didn't match. Without strict mode the test would fail for a different reason, with a confusing message. Strict mode says it clearly: "this stub wasn't used". On top of that, Mockito also reports an argument mismatch with a PotentialStubbingProblem.
The second cause is stale stubs that were copied over. The code changed and findByEmail is no longer called, but the stub stayed in the test. They make the test harder to read, so deleting them is right.
The order of fixes:
- Delete the stub or fix its argument; in 90% of cases that's enough.
- If a stub in a shared
@BeforeEachisn't needed in some tests, move it into only the tests that need it. - If it really is an optional stub, use
lenient().when(...).
Putting @MockitoSettings(strictness = Strictness.LENIENT) on the whole class is the easiest way and the worst: you switch off a useful signal.
Sign up to mark studied questions and save your progress.