python data_error ai_generated true

断言错误:预期模拟被调用 2 次。实际被调用 1 次。

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2024-03-25首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active
3.10 active

根因分析

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

English

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

generic

解决方案

  1. 90% 成功率 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% 成功率 Use mock.call_args_list to inspect actual calls and compare with expected.
    assert mock.call_args_list == [call(arg1), call(arg2)]

无效尝试

常见但无效的做法:

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

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

  2. Adding mock.reset_mock() before assertion 70% 失败

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