# 属性错误：使用 spec=MyClass 时，模拟对象没有属性 'foo'

- **ID:** `python/unittest-mock-spec-attribute`
- **领域:** python
- **类别:** type_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.9 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **** — Using spec_set=True instead of spec still raises the same error for non-existent attributes. (50% 失败率)
- **** — Removing the spec parameter entirely allows any attribute but may hide API mismatches. (60% 失败率)
