python
type_error
ai_generated
true
属性错误:Mock 对象没有属性 'some_method'
AttributeError: Mock object has no attribute 'some_method'
ID: python/attributeerror-mock-object-has-no-attribute
80%修复率
86%置信度
0证据数
2024-10-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.8 | active | — | — | — |
| 3.9 | active | — | — | — |
| 3.10 | active | — | — | — |
根因分析
创建模拟对象时未指定属性,代码尝试访问未定义的属性。
English
A mock object is created without specifying the attribute, and the code tries to access an undefined attribute.
解决方案
-
95% 成功率 Configure mock with spec or autospec
mock = Mock(spec=MyClass); mock.some_method.return_value = 42
-
90% 成功率 Set attribute directly on mock
mock = Mock(); mock.some_method = MagicMock(return_value=42)
无效尝试
常见但无效的做法:
-
Adding attribute via mock.attach_mock
60% 失败
attach_mock is for attaching additional mocks, not simple attributes.
-
Using mock.reset_mock()
80% 失败
Reset clears call history but does not add missing attributes.