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

- **ID:** `python/unittest-mock-call-order-assertion`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.8 | active | — | — |
| 3.9 | active | — | — |

## 解决方案

1. **Debug the code under test to understand why the mock is called multiple times** (90% 成功率)
   ```
   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. **Use assert_called_with to verify the arguments of the first call, then assert the total call count** (85% 成功率)
   ```
   mock.assert_called_with(1)
assert mock.call_count == 1
This verifies both the arguments and the count.
   ```

## 无效尝试

- **Changing assert_called_once to assert_called to ignore the count** — This weakens the test by not verifying the exact number of calls, which may hide regressions. (60% 失败率)
- **Adding a sleep before the assertion to allow time for calls to complete** — This does not fix the root cause; the mock is still called multiple times. (80% 失败率)
