python type_error ai_generated true

属性错误:当在不可调用的模拟对象上设置return_value时,模拟对象没有'return_value'属性

AttributeError: Mock object has no attribute 'return_value' when setting return_value on a non-callable mock

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

其他格式: JSON · Markdown 中文 · English
80%修复率
86%置信度
0证据数
2025-01-10首次发现

版本兼容性

版本状态引入弃用备注
3.8 active
3.9 active

根因分析

尝试在创建时spec=None且非可调用的Mock实例上设置return_value,但该mock被当作函数使用。

English

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

解决方案

  1. 90% 成功率 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
  2. 0% 成功率 Use side_effect instead of return_value for non-callable mocks

无效尝试

常见但无效的做法:

  1. Creating a new MagicMock instead of Mock 50% 失败

    MagicMock is callable by default, but the underlying issue may be that the mock is not intended to be callable.

  2. Setting return_value directly without checking if the mock is callable 70% 失败

    This will still raise an AttributeError if the mock is not callable.