Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Strictness and Extensions

Strict Stubs and Unnecessary Stubbing

Learn what Mockito's strictness does, why UnnecessaryStubbingException and PotentialStubbingProblem appear, the three strictness levels, and how to fix tests cleanly.

Mockito does not only help you write tests, it can also police them. Strictness is a set of checks that report dead weight in a test: stubs that were never used and calls whose arguments did not match what you stubbed. These checks catch real mistakes, such as a test that no longer exercises the path you thought it did, or a typo in an argument.

Mockito itself cannot run on this site, so the real API is shown read-only. The runnable blocks build a small stand-in that detects the same two problems on top of the Mini library, so you see how strictness works.

Where strictness comes from

With the JUnit 5 extension (@ExtendWith(MockitoExtension.class)) the default level is STRICT_STUBS. Without it, a plain Mockito.mock(...) uses a lenient default. There are three levels:

Level Behavior
LENIENT No checks. Unused stubs are fine
WARN Unused stubs print a hint to the console; tests keep passing
STRICT_STUBS Unused stubs fail the test; calls whose arguments do not match a stub of the same method fail it too

The two failures

1. UnnecessaryStubbingException. You stubbed something and nothing ever called it:

Java
@Test
void totalWithTax() {
    when(rates.vat("DE")).thenReturn(0.19);     // used
    when(rates.vat("FR")).thenReturn(0.20);     // never called: failure at the end of the test

    assertEquals(119.0, service.gross("DE", 100.0));
}

The failure message lists the unused stubbing with its line number. The fix is almost always to delete the stub, or to fix the test so the code path really runs.

2. PotentialStubbingProblem. The code called a stubbed method with different arguments:

Java
when(rates.vat("DE")).thenReturn(0.19);
service.gross("de", 100.0);   // "de" is lower-case: the stub does not match, strict mode stops the test

In lenient mode this would silently return 0.0 and the assertion would fail much later with a confusing number. Strict mode points at the real cause: you stubbed vat("DE") but the code called vat("de").

Strictness is checked at the end of each test for unused stubs, and at the moment of the call for argument mismatches.

How it works (stand-in)

Each stub in the stand-in records whether it was used. The helper Strict.check reports stubs that were never used, and calls with arguments that did not match any stub for the same method:

Java Detecting unused stubs and argument mismatches

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 unmatched call returned 100.0 (a rate of 0.0) instead of 119.0, and the helper reports two findings: the FR stub was never used, and the call with "de" did not match the "DE" stub. A real strict run would fail the test on the second one at the moment of the call and on the first one at the end.

Fixing the failures

For an unnecessary stub, ask why it was not used:

  1. The stub is leftover from an earlier version of the test. Delete it.
  2. The code under test takes a different branch than you thought. Fix the input or the branch.
  3. The stub lives in a shared @BeforeEach and only some tests use it. Move it into the tests that need it, or mark it lenient (next lesson, BDD style and lenient stubbing).

For a mismatch, correct the argument in the stub or in the call, or use a matcher if the exact value should not matter (when(rates.vat(anyString()))).

Choosing the strictness level

Java
// Per test class (JUnit 5)
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
class LegacyTest { ... }

// Without the extension: a session you open and close by hand
MockitoSession session = Mockito.mockitoSession()
        .initMocks(this)
        .strictness(Strictness.STRICT_STUBS)
        .startMocking();
try {
    // test body
} finally {
    session.finishMocking();     // this is where unused stubs are reported
}

Advice for new code: stay on STRICT_STUBS. It is a cheap reviewer that never gets tired. Use LENIENT only for old test classes you cannot clean up yet, and prefer per-stub leniency to a whole-class switch.

Strictness does not replace verify

Strict stubs tell you that a stubbed call was used. They do not tell you that a call with side effects (sending an email) happened. Keep verify(...) for outcomes and let strict stubs police inputs. A third tool, verifyNoMoreInteractions(mock), fails if the mock was used in a way you did not mention; use it sparingly, because it ties tests to implementation details (see Over-mocking and test smells).

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. When is an UnnecessaryStubbingException reported?

    Strict stubs track whether each stub was invoked and report the unused ones when the test finishes.
  2. 2. What does PotentialStubbingProblem usually indicate?

    Mockito sees a call to a method that has stubs, none of which match the arguments, and fails fast with a pointer to the mismatch.
  3. 3. Which default does MockitoExtension use?

    The JUnit 5 extension defaults to STRICT_STUBS.

Summary

  • Strictness detects unused stubs and argument mismatches; JUnit 5's MockitoExtension uses STRICT_STUBS by default.
  • Fix an unused stub by deleting it or repairing the test path; fix a mismatch by correcting the argument or using a matcher.
  • Levels: LENIENT, WARN, STRICT_STUBS; change per class with @MockitoSettings or per stub with lenient().
  • Strict stubs complement, not replace, verify.

Next: JUnit 5 extension and annotations