python
type_error
ai_generated
true
TypeError: 'MagicMock' 对象不可调用
TypeError: 'MagicMock' object is not callable
ID: python/unittest-mock-magicmock-not-callable
80%修复率
87%置信度
0证据数
2024-07-12首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在需要可调用对象的地方使用了 MagicMock 实例,但该 mock 未配置为可调用,或者错误地访问了 mock 的 return_value。
English
A MagicMock instance was used where a callable is expected, but the mock was not configured to be callable, or the mock's return_value was accessed incorrectly.
解决方案
-
95% 成功率
mock_func = MagicMock() mock_func.return_value = 42 assert mock_func() == 42
-
92% 成功率
mock_func = MagicMock() mock_func.side_effect = lambda x: x * 2 assert mock_func(5) == 10
无效尝试
常见但无效的做法:
-
85% 失败
Mock is also not callable by default. The issue is configuration, not the mock class.
-
90% 失败
If the mock is not callable, adding parentheses will still raise TypeError. The mock must be configured as callable.