# 空指针异常：无法调用“Object.getClass()”，因为“answer”为空

- **ID:** `java/mockito-when-thenreturn-null-pointer`
- **领域:** java
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

Mockito.when() 调用的方法返回 null，或者模拟对象未初始化。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 8+ | active | — | — |

## 解决方案

1. **Initialize mocks explicitly in @BeforeEach** (95% 成功率)
   ```
   @BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
}
   ```
2. **Use mock() method directly** (90% 成功率)
   ```
   MyService service = mock(MyService.class);
when(service.getData()).thenReturn("test");
   ```

## 无效尝试

- **Adding @Mock annotation without MockitoAnnotations.openMocks()** — Annotations not processed, mock remains null. (70% 失败率)
- **Using when().thenReturn() on a final method without mockito-inline** — Mockito cannot mock final methods by default, causing NPE. (60% 失败率)
