python
runtime_error
ai_generated
true
AssertionError: Expected mock to have been called once. Called 2 times.
ID: python/unittest-mock-call-order-assertion
80%Fix Rate
87%Confidence
0Evidence
2025-06-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
Root Cause
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中文
模拟对象被调用的次数超过预期,通常是由于被测代码多次调用被模拟的函数,而预期只应调用一次。
Workarounds
-
90% success 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.
-
85% success 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.
Dead Ends
Common approaches that don't work:
-
Changing assert_called_once to assert_called to ignore the count
60% fail
This weakens the test by not verifying the exact number of calls, which may hide regressions.
-
Adding a sleep before the assertion to allow time for calls to complete
80% fail
This does not fix the root cause; the mock is still called multiple times.