Question
Why is Mockito's when() method returning a null pointer exception?
Mockito.when(mockedObject.method()).thenReturn(value);
Answer
When using Mockito's when() method, encountering a null pointer exception typically indicates that the behavior of a mocked object has not been properly defined or the mock itself is not initialized correctly. This guide will outline common causes of this error and their solutions to help you efficiently handle this issue in your unit tests.
Mockito.when(mockedObject.method()).thenReturn(value);
Causes
- The mock object has not been instantiated. Ensure that you have properly created the mock using Mockito.mock() or the @Mock annotation.
- The method being stubbed is not a method that has been mocked. If you call when() on a non-mocked object, it will lead to a null pointer exception.
- Incorrectly chaining method calls can cause issues. Verify that the method specified in when() matches the method signature exactly.
Solutions
- Ensure that all mock objects are properly initialized before use, preferably with `MockitoAnnotations.initMocks(this)` in your setup method.
- Double-check to verify that the method within the when() statement corresponds exactly with the mocked object's method to avoid discrepancies.
- Utilize ArgumentMatchers if your method involves parameters, e.g., `when(mock.method(anyString())).thenReturn(value);`. This ensures that any parameters passed will not cause a failure.
Common Mistakes
Mistake: Forgetting to initialize mocks before usage.
Solution: Use MockitoAnnotations.initMocks(this) in your test setup.
Mistake: Not checking the mock object's state before using it in tests.
Solution: Add assertions or logs to ensure the mock is not null before the when() call.
Mistake: Using the concrete implementation of a class instead of its mock.
Solution: Always mock the interface or abstract class to avoid invoking real methods.
Helpers
- Mockito when() method
- null pointer exception Mockito
- Mockito testing tips
- fix Mockito null pointer exception
- Mockito common issues