python type_error ai_generated true

AttributeError: 'function' object has no attribute 'return_value'

ID: python/unittest-mock-return-value-attribute

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2025-06-30First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active

Root Cause

Trying to set return_value on a regular function instead of a Mock object, often because the patch decorator was not applied correctly or the target is not a mock.

generic

中文

尝试在常规函数上设置 return_value,而不是在 Mock 对象上,通常是因为 patch 装饰器未正确应用或目标不是模拟对象。

Workarounds

  1. 90% success
    Ensure the patch decorator is applied to the test function: @patch('module.function') def test(mock_func): mock_func.return_value = 42
  2. 85% success
    Use patch as a context manager: with patch('module.function') as mock_func: mock_func.return_value = 42

Dead Ends

Common approaches that don't work:

  1. 50% fail

    Wrapping the function in a Mock manually may work but bypasses the patch mechanism and can cause test isolation issues.

  2. 60% fail

    Using patch.object with a string instead of the actual object may still fail if the attribute does not exist.