java runtime_error ai_generated true

org.mockito.exceptions.stubbing.AnswerException: Exception thrown by answer: java.lang.RuntimeException: test exception

ID: java/mockito-answer-throws-exception

Also available as: JSON · Markdown · 中文
80%Fix Rate
84%Confidence
0Evidence
2024-08-25First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
8+ active

Root Cause

Custom Answer implementation throws an exception when invoked during test.

generic

中文

自定义 Answer 实现 在测试调用期间抛出异常。

Workarounds

  1. 90% success Fix Answer implementation to handle edge cases
    Answer<String> answer = invocation -> {
        if (invocation.getArgument(0) == null) {
            return "default";
        }
        return invocation.getArgument(0).toString();
    };
  2. 85% success Use thenAnswer with lambda
    when(mock.method(any())).thenAnswer(invocation -> {
        // safe logic
        return "result";
    });

Dead Ends

Common approaches that don't work:

  1. Catching exception in test and ignoring 60% fail

    Hides the real issue; test may pass incorrectly.

  2. Using thenThrow instead of custom Answer 40% fail

    May not match the intended behavior if Answer has complex logic.