> For the complete documentation index, see [llms.txt](https://zhouhao4221.gitbook.io/haiqing-docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/test-generation.md).

# 测试编写

为新写的或现有的代码生成测试用例初稿。适合工具函数、API 适配器、服务类。核心业务逻辑的测试须人工编写，生成的测试需要人工审查边界情况。

***

## 什么时候用

* 实现了新函数，需要测试覆盖
* 已有代码没有测试，准备补写
* 重构后需要验证行为未变

不适合：测试策略决策（测什么、测到什么程度）——那是架构判断，不是生成任务。

## 准备什么

* **被测代码**：函数或模块的完整代码
* **测试框架**：具体说明（Jest、pytest、Go test……），否则 AI 可能猜错
* **已知边界条件**：你已经想到的需要特别覆盖的边界情况（可以不填，AI 会自行识别，但你想到的填进去更可靠）
* **不能 mock 的东西**：如果有不希望 AI mock 掉的依赖，提前说明

## 怎么触发

**单次任务**

```
先读 04-prompt/code/test-generation.md，
被测代码在 [文件路径]，
测试框架：[框架名]，
[已知需要覆盖的边界：可选]。
请先列出测试场景清单，确认后再生成代码。
```

"先列清单再生成代码"这一步很重要。清单确认了再写代码，比直接生成一堆测试再逐个检查效率高得多。

**写入 CLAUDE.md**

```markdown
## 测试
生成测试时，先输出测试场景清单（happy path + 边界 + 错误路径），
确认场景完整后再写代码。不要 mock 核心业务逻辑，只 mock 外部依赖。
```

## 好的输出是什么样的

* 先给测试场景清单，再给代码（不直接跳到代码）
* 覆盖三类场景：正常输入（happy path）、边界值（空值、零值、最大值）、错误路径（非法输入、依赖失败）
* 每个测试只测一件事，测试名描述场景而不是描述函数名
* 没有永远通过的断言（`assertTrue(true)` 这类）
* 标注哪些场景需要人工补充（比如依赖真实外部服务的集成测试）

## 常见失败模式

* **只测 happy path**：没有给已知边界条件，AI 倾向于只测正常情况。把你已经知道的边界填进去
* **mock 了业务逻辑**：AI 为了让测试通过，把核心逻辑 mock 掉了。测试变成了"测 mock 配置"。明确说明哪些不能 mock
* **测试永远通过**：断言太宽松，测任何输入都通过。审查时重点看断言是否会在错误场景下失败
* **测实现不测行为**：测试直接调用私有方法或检查内部状态。让 AI 只通过公开接口测试

***

## 版本历史

* v1.0：初始版本


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://zhouhao4221.gitbook.io/haiqing-docs/04-prompt/code/test-generation.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
