python data_error ai_generated true

AssertionError: Expected mock to be called 2 times. Called 1 times.

ID: python/unittest-mock-call-count-error

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active
3.9 active
3.10 active

Root Cause

The code under test calls the mocked function fewer times than expected, often due to conditional logic or early returns.

generic

中文

被测试的代码调用模拟函数的次数少于预期,通常是由于条件逻辑或提前返回。

Workarounds

  1. 90% success Debug the code to understand why the function is not called enough times.
    Add print statements or use a debugger to trace the execution path.
  2. 85% success Use mock.call_args_list to inspect actual calls and compare with expected.
    assert mock.call_args_list == [call(arg1), call(arg2)]

Dead Ends

Common approaches that don't work:

  1. Increasing the expected call count to match actual calls 80% fail

    This masks the bug in the code that is not calling the function enough times.

  2. Adding mock.reset_mock() before assertion 70% fail

    Resetting the mock clears call history, making the assertion pass incorrectly.