python
type_error
ai_generated
true
TypeError: 'MagicMock' object is not callable
ID: python/unittest-mock-magicmock-not-callable
80%Fix Rate
87%Confidence
0Evidence
2024-07-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.x | active | — | — | — |
Root Cause
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.
generic中文
在需要可调用对象的地方使用了 MagicMock 实例,但该 mock 未配置为可调用,或者错误地访问了 mock 的 return_value。
Workarounds
-
95% success
mock_func = MagicMock() mock_func.return_value = 42 assert mock_func() == 42
-
92% success
mock_func = MagicMock() mock_func.side_effect = lambda x: x * 2 assert mock_func(5) == 10
Dead Ends
Common approaches that don't work:
-
85% fail
Mock is also not callable by default. The issue is configuration, not the mock class.
-
90% fail
If the mock is not callable, adding parentheses will still raise TypeError. The mock must be configured as callable.