python type_error ai_generated true

TypeError: 'MagicMock' 对象不可调用

TypeError: 'MagicMock' object is not callable

ID: python/unittest-mock-magicmock-not-callable

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 95% 成功率
    mock_func = MagicMock()
    mock_func.return_value = 42
    assert mock_func() == 42
  2. 92% 成功率
    mock_func = MagicMock()
    mock_func.side_effect = lambda x: x * 2
    assert mock_func(5) == 10

无效尝试

常见但无效的做法:

  1. 85% 失败

    Mock is also not callable by default. The issue is configuration, not the mock class.

  2. 90% 失败

    If the mock is not callable, adding parentheses will still raise TypeError. The mock must be configured as callable.