python
type_error
ai_generated
true
AttributeError: Mock object has no attribute 'return_value' when setting return_value on a non-callable mock
ID: python/unittest-mock-return-value-override
80%Fix Rate
86%Confidence
0Evidence
2025-01-10First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
Root Cause
Attempting to set return_value on a Mock instance that was created with spec=None and not as a callable, but the mock is being used as if it were a function.
generic中文
尝试在创建时spec=None且非可调用的Mock实例上设置return_value,但该mock被当作函数使用。
Workarounds
-
90% success Ensure the mock is created as a callable by using MagicMock or by passing spec=SomeCallable
from unittest.mock import MagicMock mock = MagicMock() mock.return_value = 42 result = mock() # Works Or: mock = Mock(spec=lambda: None) mock.return_value = 42
-
0% success Use side_effect instead of return_value for non-callable mocks
Dead Ends
Common approaches that don't work:
-
Creating a new MagicMock instead of Mock
50% fail
MagicMock is callable by default, but the underlying issue may be that the mock is not intended to be callable.
-
Setting return_value directly without checking if the mock is callable
70% fail
This will still raise an AttributeError if the mock is not callable.