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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

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

无效尝试

常见但无效的做法:

  1. Adding @Mock annotation without MockitoAnnotations.openMocks() 70% 失败

    Annotations not processed, mock remains null.

  2. Using when().thenReturn() on a final method without mockito-inline 60% 失败

    Mockito cannot mock final methods by default, causing NPE.