python runtime_error ai_generated true

断言错误:期望模拟对象被调用一次。实际被调用2次。

AssertionError: Expected mock to have been called once. Called 2 times.

ID: python/unittest-mock-call-order-assertion

其他格式: JSON · Markdown 中文 · English
80%修复率
87%置信度
0证据数
2025-06-05首次发现

版本兼容性

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

根因分析

模拟对象被调用的次数超过预期,通常是由于被测代码多次调用被模拟的函数,而预期只应调用一次。

English

The mock object was called more times than expected, often due to the code under test calling the mocked function multiple times when it should only be called once.

generic

解决方案

  1. 90% 成功率 Debug the code under test to understand why the mock is called multiple times
    Add print statements or use a debugger to trace calls. For example:
    mock.assert_has_calls([call(1), call(2)])
    Then adjust the code to ensure it calls the mock only once.
  2. 85% 成功率 Use assert_called_with to verify the arguments of the first call, then assert the total call count
    mock.assert_called_with(1)
    assert mock.call_count == 1
    This verifies both the arguments and the count.

无效尝试

常见但无效的做法:

  1. Changing assert_called_once to assert_called to ignore the count 60% 失败

    This weakens the test by not verifying the exact number of calls, which may hide regressions.

  2. Adding a sleep before the assertion to allow time for calls to complete 80% 失败

    This does not fix the root cause; the mock is still called multiple times.