python
type_error
ai_generated
true
属性错误:'function' 对象没有属性 'return_value'
AttributeError: 'function' object has no attribute 'return_value'
ID: python/unittest-mock-return-value-attribute
80%修复率
88%置信度
0证据数
2025-06-30首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
根因分析
尝试在常规函数上设置 return_value,而不是在 Mock 对象上,通常是因为 patch 装饰器未正确应用或目标不是模拟对象。
English
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.
解决方案
-
90% 成功率
Ensure the patch decorator is applied to the test function: @patch('module.function') def test(mock_func): mock_func.return_value = 42 -
85% 成功率
Use patch as a context manager: with patch('module.function') as mock_func: mock_func.return_value = 42
无效尝试
常见但无效的做法:
-
50% 失败
Wrapping the function in a Mock manually may work but bypasses the patch mechanism and can cause test isolation issues.
-
60% 失败
Using patch.object with a string instead of the actual object may still fail if the attribute does not exist.