java
runtime_error
ai_generated
true
空指针异常:无法调用“Object.getClass()”,因为“answer”为空
java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "answer" is null
ID: java/mockito-when-thenreturn-null-pointer
80%修复率
85%置信度
0证据数
2024-03-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 8+ | active | — | — | — |
根因分析
Mockito.when() 调用的方法返回 null,或者模拟对象未初始化。
English
Mockito.when() called with a method that returns null, or the mock object is not initialized.
解决方案
-
95% 成功率 Initialize mocks explicitly in @BeforeEach
@BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } -
90% 成功率 Use mock() method directly
MyService service = mock(MyService.class); when(service.getData()).thenReturn("test");
无效尝试
常见但无效的做法:
-
Adding @Mock annotation without MockitoAnnotations.openMocks()
70% 失败
Annotations not processed, mock remains null.
-
Using when().thenReturn() on a final method without mockito-inline
60% 失败
Mockito cannot mock final methods by default, causing NPE.