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
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.
解决方案
-
80% 成功率
Add the missing attribute to MyClass or use a mock with spec=MyClass and then add the attribute dynamically: mock.foo = MagicMock()
-
85% 成功率
Use autospec=True instead of spec to automatically create a mock that matches the class's interface.
无效尝试
常见但无效的做法:
-
50% 失败
Using spec_set=True instead of spec still raises the same error for non-existent attributes.
-
60% 失败
Removing the spec parameter entirely allows any attribute but may hide API mismatches.