python type_error ai_generated true

AssertionError: Expected mock to be called once. Called 0 times.

ID: python/unittest-mock-return-value-not-set

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2024-01-22First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.8 active

Root Cause

在使用unittest.mock时,mock对象没有正确配置return_value或side_effect,导致测试中的调用没有被正确模拟,实际调用次数为0。

generic

中文

unittest.mock中,mock对象未设置return_value或side_effect,导致调用未被模拟,实际调用次数为0。

Workarounds

  1. 95% success
    mock_obj.return_value = 'expected_value'
    result = mock_obj()
    assert result == 'expected_value'
  2. 90% success
    with patch('module.func') as mock_func:
        mock_func.side_effect = [1, 2]
        assert module.func() == 1

Dead Ends

Common approaches that don't work:

  1. 80% fail

    导入错误不是主要原因,mock配置才是根本问题。

  2. 90% fail

    这掩盖了问题,而不是修复mock配置。