# AttributeError: 'TestUser' 对象没有属性 'db'

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

## 根因

setUpClass 或 setUp 静默失败（或拼写错误），导致 setUp 中赋值的属性从未创建，但 tearDown 仍引用它。

## 版本兼容性

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

## 解决方案

1. **** (85% 成功率)
   ```
   class TestUser(unittest.TestCase):
    def setUp(self):
        self.db = connect()

    def tearDown(self):
        if hasattr(self, 'db'):
            self.db.close()
   ```
2. **** (95% 成功率)
   ```
   def setUp(self):
    self.db = connect()
    self.addCleanup(self.db.close)
   ```

## 无效尝试

- **** — Hides the real setup failure; subsequent tests may run against a half-initialized state. (80% 失败率)
- **** — If setUp is the failing method, referencing the attribute earlier just moves the error. (70% 失败率)
