Mockito - NullpointerException when stubbing Method
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.
Mockito is a popular framework used for testing Java applications, providing the ability to create mock objects and define their behavior. However, one common issue developers encounter when using Mockito is the NullPointerException that occurs when stubbing methods. This article provides a detailed analysis of this issue, explores its causes, and suggests best practices to resolve it.
Understanding Mockito and NullPointerException
Mockito allows developers to mock parts of their application to isolate and test individual components without relying on external dependencies. Stubbing methods in Mockito involves specifying behaviors of a mock object. For example, you might want a method getStatus() to return "OK" when called on a mock object.
Example of Stubbing in Mockito
In this example, we use when(mockedObject.getStatus()).thenReturn("OK"); to define the return value of getStatus(). However, developers sometimes encounter a NullPointerException during stubbing or execution, which can be perplexing.
Common Causes of NullPointerException in Stubbing
1. Mock Object Initialization
A frequent cause for NullPointerException is improper initialization of mock objects. If the mock is not created correctly, stubbing methods will not work as expected.
Solution:
Ensure the creation of the mock is done using the Mockito.mock() method. For instance:
2. Method Chaining
Method chaining is another scenario where NullPointerException can occur if intermediate calls return null.
In this example, if getNestedObject() returns null, a NullPointerException will occur when attempting to stub getValue().
Solution: You may need to mock the nested object as well:
3. Incorrect Use of when() Function
Incorrectly setting up when() statements can also lead to NullPointerException. It often occurs when the when() function is called with an invalid or null argument.
Solution:
Ensure that all inputs to when() calls are valid and the methods being stubbed are not called before stubbing.
Best Practices to Avoid NullPointerException
- Always Initialize Mocks Properly: Use
Mockito.mock()appropriately. Consider using annotations with@Mockand@Beforetogether withMockitoAnnotations.initMocks(this);for cleaner setups. - Use
@InjectMocksto Inject Mock Dependencies: When a class has dependencies, use the@InjectMocksannotation to inject mocked dependencies. - Mock Chained or Nested Calls: For methods returning other objects, ensure those intermediate objects are also mocked.
- Utilize Argument Matchers: Use argument matchers like
anyInt(),anyString(), etc., to avoidNullPointerExceptiondue to specific, incorrect argument values. - Verify Mock Interactions: Use
Mockito.verify()to ensure methods on mocks are called with correct parameters for further debugging insights.
Debugging NullPointerException in Mockito
Checkpoints:
- Verify that all necessary setup and initialization has been done before running the test.
- Double-check the method calls in your
when()clauses to ensure they are designed to return non-null values. - Make sure you understand the call hierarchy in your mock objects to properly set up all necessary return values.
Summary Table
Cause of NullPointerException | Description | Solution |
| Improper Mock Initialization | Failing to correctly initialize a mock leads to null values. | Use Mockito.mock() or annotations like @Mock with MockitoAnnotations.initMocks(this);. |
| Method Chaining | Intermediate method calls may return null, leading to errors. | Mock nested objects and control return values for all levels. |
Incorrect Use of when() | Passing invalid arguments or calling methods that should be stubbed can throw exceptions. | Ensure correct method arguments and verify proper call sequences before the test executes. |
| Uninitialized Dependencies | External dependencies not mocked or initialized, leading to unexpected null returns. | Employ @InjectMocks to auto-inject mocks into tested classes. |
In conclusion, while NullPointerException during stubbing in Mockito can be challenging, understanding its causes allows you to effectively mitigate this issue. By adhering to best practices and methodically verifying your mock setup, you can write robust tests, ensuring component isolation and validation of your application logic.
Related reading
- Mockito - Spy vs Mock
- Mockito doAnswer Vs thenReturn
- Mockito error in Spring Boot tests after migrating to JDK 11
- Mockito How to mock and assert a thrown exception?
- Mockito how to verify method was called on an object created within a method?
- Mockito Inject real objects into private @Autowired fields
- Mockito InvalidUseOfMatchersException
- Mockito is currently self-attaching to enable the inline-mock-maker. This will no longer work in future releases of the JDK

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
Interview Questions practice on Codemia
Over 8,000 real interview questions from top companies, searchable by company and role.