# 属性错误：使用 autospec 时，模拟对象没有属性 'non_existent_method'

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

## 根因

在 patch 或 create_autospec 中使用 autospec=True 会将模拟限制为仅具有原始对象上存在的属性，访问不存在的属性会引发 AttributeError。

## 版本兼容性

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

## 解决方案

1. **** (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)
   ```
2. **** (75% 成功率)
   ```
   Use spec_set instead of autospec to allow additional attributes while still checking existing ones.
   ```

## 无效尝试

- **** — Disabling autospec (autospec=False) may allow the test to pass but hides potential mismatches between the mock and the real API. (50% 失败率)
- **** — Adding the missing attribute to the original object may not be feasible if it's a third-party library. (40% 失败率)
