python type_error ai_generated true

属性错误:使用 spec=MyClass 时,模拟对象没有属性 'foo'

AttributeError: Mock object has no attribute 'foo' when using spec=MyClass

ID: python/unittest-mock-spec-attribute

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

版本兼容性

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

根因分析

使用 spec=MyClass 创建模拟对象会限制模拟仅具有 MyClass 上存在的属性,访问不存在的属性会引发 AttributeError。

English

Creating a mock with spec=MyClass restricts the mock to only have attributes that exist on MyClass, and accessing a non-existent attribute raises an AttributeError.

generic

解决方案

  1. 80% 成功率
    Add the missing attribute to MyClass or use a mock with spec=MyClass and then add the attribute dynamically: mock.foo = MagicMock()
  2. 85% 成功率
    Use autospec=True instead of spec to automatically create a mock that matches the class's interface.

无效尝试

常见但无效的做法:

  1. 50% 失败

    Using spec_set=True instead of spec still raises the same error for non-existent attributes.

  2. 60% 失败

    Removing the spec parameter entirely allows any attribute but may hide API mismatches.