python runtime_error ai_generated true

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

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

Also available as: JSON · Markdown · 中文
80%Fix Rate
87%Confidence
0Evidence
2026-10-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

The test asserts mock.assert_called_with or mock.assert_called_once, but the actual number of calls does not match the expectation, often due to conditional logic in the code under test.

generic

中文

测试断言了 mock.assert_called_with 或 mock.assert_called_once,但实际调用次数与预期不符,通常是由于被测试代码中的条件逻辑。

Workarounds

  1. 85% success
    Debug the code under test to understand the call pattern and adjust the expected count or the code logic.
  2. 80% success
    Use mock.call_count to get the actual count and assert conditionally: self.assertEqual(mock.call_count, 3)

Dead Ends

Common approaches that don't work:

  1. 60% fail

    Adding extra mock calls to meet the expected count may pass the test but does not reflect real behavior.

  2. 50% fail

    Using assert_any_call instead of assert_called_with may pass if the call exists but does not verify the exact number of calls.