# 运行时错误: 没有异步客户端时TestClient不能用于异步函数。

- **ID:** `python/fastapi-test-client-error`
- **领域:** python
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 80%

## 根因

使用FastAPI的TestClient测试异步路由时，未使用异步客户端或事件循环。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| 3.x | active | — | — |

## 解决方案

1. **使用TestClient的async模式** (95% 成功率)
   ```
   from fastapi.testclient import TestClient; from main import app; client = TestClient(app); with client: response = client.get('/async-endpoint')
   ```
2. **使用httpx.AsyncClient直接测试** (90% 成功率)
   ```
   from httpx import AsyncClient; async with AsyncClient(app=app, base_url='http://test') as ac: response = await ac.get('/async-endpoint')
   ```

## 无效尝试

- **在同步测试函数中直接调用异步路由** — TestClient默认同步。 (90% 失败率)
- **使用pytest-asyncio但不配置** — 需要正确标记测试函数。 (70% 失败率)
