Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 37 ยท Patterns and Pitfalls

Troubleshooting Common Mockito Errors

Decode the Mockito errors you will meet: NullPointerException on mocks, stubs that do not match, UnfinishedStubbing, InvalidUseOfMatchers, WrongTypeOfReturnValue and more, with causes and fixes.

Mockito's error messages are unusually good: they usually name the problem, show the line, and suggest a fix. They can still look intimidating the first time. This lesson is a field guide to the failures you will really meet, grouped by symptom, with the cause behind each and the standard remedy. Two of the most common causes (an argument that does not match, and an unstubbed null) are reproduced in runnable Java with the Mini stand-in.

Mockito is not available on this site, so the messages are described in words and real code is read-only.

1. NullPointerException on a mock's result

Symptom: the exception is thrown in your code, not in Mockito.

Cause: you did not stub the method, so the mock returned its default (null for objects). Or the stub did not match (see problem 2).

Java The unstubbed null and the missing equals

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 second half shows an important rule: Mockito matches arguments with equals. Product does not override it, so two instances with the same SKU are different arguments. Fixes: implement equals/hashCode (a record does it for you), pass the same instance, or use a matcher such as any(Product.class) or argThat(p -> p.sku.equals("A-1")).

2. The stub "does nothing" / wrong value returned

Checklist:

  • Is the argument equal (see above)? A long and an int do not match each other, and 1L is not 1.
  • Was the stub made after the call it should affect?
  • Are you stubbing the same mock instance that the class under test uses? With @InjectMocks and two mocks of one type, injection may go by name to the wrong one.
  • Did a later stub override this one? The last matching stub wins.
  • Are you stubbing a method the code does not call (it calls an overload)?

Strict stubs (see Strict stubs) point at several of these automatically.

3. UnfinishedStubbingException

You started stubbing and then did something else before finishing. Typical form:

Java
when(repo.find(1))                 // forgot .thenReturn(...)
verify(repo).save(any());          // error: previous stubbing is unfinished

Another form: calling a method of another mock inside the argument of thenReturn:

Java
when(a.value()).thenReturn(b.compute());   // b.compute() is a mock call in the middle of stubbing a

Fix: compute the value first, then stub.

Java
int computed = b.compute();
when(a.value()).thenReturn(computed);

4. InvalidUseOfMatchersException

Cause: matchers used outside a stubbing or verification, or mixed with raw values in one call.

Java
verify(repo).save(any(), "ana");       // error: if one argument is a matcher, all must be
verify(repo).save(any(), eq("ana"));   // fixed

Also error: a matcher returned from a helper that was evaluated away from the stubbing line, or the use of any() as a plain value in code under test. The matcher chapter covers this in depth.

5. WrongTypeOfReturnValue

You used doReturn (which is not type-checked) with the wrong type:

Java
doReturn("19").when(rates).vat("DE");    // vat returns double

Fix the type. It also happens when a stub is attached to the wrong call because of a typo in a chain.

6. MissingMethodInvocationException: when() requires an argument which has to be 'a method call on a mock'

You passed something to when(...) that is not a call to a mock: a call on a real object, a final method with the old mock maker, a private method, or a static method.

Java
when(realList.size()).thenReturn(3);     // realList is not a mock or spy

Fix: make it a mock or spy, use the inline mock maker for final or static cases, or restructure.

7. NotAMockException

You called verify(x) or when(x...) where x is not a mock, often after wrapping the mock in a decorator or passing the wrong variable.

8. TooManyActualInvocations / WantedButNotInvoked

verify found a different call count. The message lists the actual calls and the line numbers, and for a wanted-but-not-invoked mismatch it also lists similar invocations with different arguments. Read that list: it is usually an argument problem (equals again) or a call to another overload.

The stand-in imitates this failure text:

Java Reading a verification failure

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.

When a verification fails, print or read the actual calls first. The difference (one character here) is almost always visible at once.

9. Mockito cannot mock this class

Messages mention a type that cannot be mocked: a primitive, a wrapper, String, Class, or an anonymous or local class in some cases. Mock the interface instead or use the real object. For final or static issues, see Final classes and the inline mock maker.

10. Problems in test setup

Symptom Likely cause
All @Mock fields are null No @ExtendWith(MockitoExtension.class) or openMocks call; or the test class is JUnit 4 style with a JUnit 5 runner mismatch
@InjectMocks field is null or has null dependencies The constructor could not be satisfied by mock types, or the class is abstract
Mocks from one test leak into the next Static or shared fields holding mocks; use per-test instances
Mockito cannot mock this class on startup Missing agent or old JDK, or the mockito-extensions file pins an incompatible mock maker
Warning about dynamic agent loading on a newer JDK Attach Mockito as a Java agent in the build configuration

11. Hidden state: Mockito.reset and leaks

Calling reset(mock) in the middle of a test removes all stubs and recorded interactions. Needing it usually means a test does too much; split it. For a clean slate between tests, rely on per-test mocks and not on resets. validateMockitoUsage() (called for you by the extension) detects stubbing that was started but not completed, one cause of confusing errors in the next test.

A debugging routine

  1. Read the full message; Mockito lists related calls and line numbers.
  2. Print mockingDetails(mock).getInvocations() to see what was really called.
  3. Check argument equality (equals) and numeric types.
  4. Turn on withSettings().verboseLogging() for one mock.
  5. Reduce: copy the failing case into a tiny test with one mock.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. A stub with new Product("A-1") never matches a call made with another new Product("A-1"). What is the usual cause?

    Argument matching uses equals. Implement equals/hashCode (records do), reuse the instance, or use a matcher.
  2. 2. What typically causes UnfinishedStubbingException?

    A stubbing was started and another Mockito call happened before it was finished.
  3. 3. How do you fix verify(repo).save(any(), "ana") raising InvalidUseOfMatchersException?

    When one argument uses a matcher, every argument must be a matcher; wrap raw values with eq().

Summary

  • Match failures usually mean equals or numeric-type differences; read the actual invocations Mockito lists.
  • UnfinishedStubbing: finish each when(...) before doing anything else; compute values first.
  • InvalidUseOfMatchers: all arguments must be matchers or none.
  • WrongTypeOfReturnValue comes from doReturn with a wrong type; when() on a non-mock gives MissingMethodInvocation.
  • Debug by printing invocations, enabling verbose logging and shrinking the test.

Next: Project: order service