python
type_error
ai_generated
true
属性错误:使用 autospec 时,模拟对象没有属性 'non_existent_method'
AttributeError: Mock object has no attribute 'non_existent_method' when using autospec
ID: python/unittest-mock-autospec-attribute-error
80%修复率
84%置信度
0证据数
2026-07-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.9 | active | — | — | — |
根因分析
在 patch 或 create_autospec 中使用 autospec=True 会将模拟限制为仅具有原始对象上存在的属性,访问不存在的属性会引发 AttributeError。
English
Using autospec=True in patch or create_autospec restricts the mock to only have attributes that exist on the original object, and accessing a non-existent attribute raises an AttributeError.
解决方案
-
85% 成功率
Ensure the attribute exists on the original object, or use autospec with a spec object that includes the attribute: create_autospec(MyClass, instance=True)
-
75% 成功率
Use spec_set instead of autospec to allow additional attributes while still checking existing ones.
无效尝试
常见但无效的做法:
-
50% 失败
Disabling autospec (autospec=False) may allow the test to pass but hides potential mismatches between the mock and the real API.
-
40% 失败
Adding the missing attribute to the original object may not be feasible if it's a third-party library.