# starlette.testclient.TestClient: Connection refused

- **ID:** `python/starlette-testclient-connection-error`
- **Domain:** python
- **Category:** network_error
- **Verification:** ai_generated
- **Fix Rate:** 80%

## Root Cause

TestClient 尝试连接未启动的应用服务器，或应用启动失败。

## Version Compatibility

| Version | Status | Introduced | Deprecated |
|---------|--------|------------|------------|
| 3.x | active | — | — |

## Workarounds

1. **** (95% success)
   ```
   使用 with TestClient(app) as client: 确保生命周期管理
   ```
2. **** (90% success)
   ```
   检查应用是否在 __main__ 中启动，并确保测试使用相同实例
   ```
3. **** (85% success)
   ```
   使用 httpx 的 ASGITransport 替代 TestClient
   ```

## Dead Ends

- **** — 根本原因不是超时，而是服务器未运行。 (60% fail)
- **** — 绕过 TestClient 的 ASGI 支持，可能导致上下文错误。 (50% fail)
- **** — 可能引起端口占用或资源泄漏。 (70% fail)
