java
runtime_error
ai_generated
true
java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "answer" is null
ID: java/mockito-when-thenreturn-null-pointer
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 8+ | active | — | — | — |
Root Cause
Mockito.when() called with a method that returns null, or the mock object is not initialized.
generic中文
Mockito.when() 调用的方法返回 null,或者模拟对象未初始化。
Workarounds
-
95% success Initialize mocks explicitly in @BeforeEach
@BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } -
90% success Use mock() method directly
MyService service = mock(MyService.class); when(service.getData()).thenReturn("test");
Dead Ends
Common approaches that don't work:
-
Adding @Mock annotation without MockitoAnnotations.openMocks()
70% fail
Annotations not processed, mock remains null.
-
Using when().thenReturn() on a final method without mockito-inline
60% fail
Mockito cannot mock final methods by default, causing NPE.