java runtime_error ai_generated true

java.lang.NullPointerException: Cannot invoke "Object.getClass()" because "answer" is null

ID: java/mockito-when-thenreturn-null-pointer

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
0Evidence
2024-03-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

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

Dead Ends

Common approaches that don't work:

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

    Annotations not processed, mock remains null.

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

    Mockito cannot mock final methods by default, causing NPE.