从 0 到 1 创建 AI Testing Agent
2026/7/20大约 5 分钟
从 0 到 1 创建 AI Testing Agent
前言
前面两篇文章我们分别讨论了:
现在,是时候更进一步了——创建一个能独立完成测试任务的 AI Testing Agent。
什么是 AI Testing Agent?
AI Testing Agent 是一个能够:
- 🧠 理解测试需求——解析自然语言描述的测试场景
- 🔧 自主选择工具——决定使用哪个测试框架、哪个浏览器
- 📝 生成测试代码——编写并执行测试脚本
- 📊 分析测试结果——判断通过/失败,给出修复建议
- 🔄 迭代优化——根据反馈不断改进测试策略
简单来说,它是一个能独立思考和行动的测试工程师数字分身。
Agent 架构设计
整体架构
graph TB
User[用户输入测试需求] --> Orchestrator[Agent 编排器]
Orchestrator --> Planner[测试计划器]
Orchestrator --> Executor[测试执行器]
Orchestrator --> Analyzer[结果分析器]
Planner --> ToolRegistry[工具注册中心]
Executor --> ToolRegistry
Analyzer --> ToolRegistry
ToolRegistry --> PlaywrightMCP[Playwright MCP]
ToolRegistry --> APITool[API 测试工具]
ToolRegistry --> AssertTool[断言工具]
ToolRegistry --> ReportTool[报告工具]
Analyzer --> Report[测试报告]核心组件
1. Agent 编排器(Orchestrator)
负责接收用户指令,协调各组件工作:
用户输入 → 解析意图 → 制定计划 → 分配任务 → 汇总结果2. 测试计划器(Planner)
根据需求生成测试策略和用例清单:
- 分析测试范围
- 确定测试类型(功能/性能/安全)
- 生成测试用例概要
3. 测试执行器(Executor)
调用具体的 MCP 工具执行测试:
- 浏览器操作(通过 Playwright MCP)
- API 调用
- 断言验证
- 截图/录屏
4. 结果分析器(Analyzer)
对测试结果进行分析:
- 判断通过/失败
- 分析失败原因
- 生成修复建议
- 输出测试报告
实战:构建第一个 Agent
项目结构
ai-testing-agent/
├── src/
│ ├── agent/
│ │ ├── orchestrator.ts # 编排器
│ │ ├── planner.ts # 计划器
│ │ ├── executor.ts # 执行器
│ │ └── analyzer.ts # 分析器
│ ├── tools/
│ │ ├── registry.ts # 工具注册
│ │ ├── playwright.ts # Playwright 工具
│ │ ├── api.ts # API 工具
│ │ └── assert.ts # 断言工具
│ ├── prompts/
│ │ ├── planner.md # 计划器 Prompt
│ │ ├── executor.md # 执行器 Prompt
│ │ └── analyzer.md # 分析器 Prompt
│ └── index.ts # 入口
├── tests/
│ └── agent.test.ts
├── package.json
└── tsconfig.jsonStep 1: 工具注册中心
// src/tools/registry.ts
interface Tool {
name: string;
description: string;
execute: (params: Record<string, any>) => Promise<ToolResult>;
}
class ToolRegistry {
private tools: Map<string, Tool> = new Map();
register(tool: Tool): void {
this.tools.set(tool.name, tool);
}
getToolNames(): string[] {
return Array.from(this.tools.keys());
}
getToolDescription(): string {
return Array.from(this.tools.values())
.map(t => `- ${t.name}: ${t.description}`)
.join('\n');
}
async execute(name: string, params: Record<string, any>): Promise<ToolResult> {
const tool = this.tools.get(name);
if (!tool) throw new Error(`Tool "${name}" not found`);
return tool.execute(params);
}
}Step 2: 编排器实现
// src/agent/orchestrator.ts
interface TaskRequest {
description: string; // 测试需求描述
target: string; // 测试目标 URL
browser?: string; // 浏览器类型
timeout?: number; // 超时时间
}
interface TaskResult {
success: boolean;
testCases: TestCase[];
executionResults: ExecutionResult[];
report: TestReport;
}
class Orchestrator {
private planner: Planner;
private executor: Executor;
private analyzer: Analyzer;
constructor() {
this.planner = new Planner();
this.executor = new Executor();
this.analyzer = new Analyzer();
}
async executeTask(request: TaskRequest): Promise<TaskResult> {
console.log(`🚀 开始执行测试任务: ${request.description}`);
// 1. 制定测试计划
console.log('📋 阶段 1/3: 制定测试计划...');
const plan = await this.planner.createPlan(request);
// 2. 执行测试用例
console.log(`🔄 阶段 2/3: 执行 ${plan.testCases.length} 个测试用例...`);
const executionResults = await this.executor.execute(plan.testCases);
// 3. 分析结果并生成报告
console.log('📊 阶段 3/3: 分析结果并生成报告...');
const report = await this.analyzer.analyze(executionResults);
return {
success: report.passed === report.total,
testCases: plan.testCases,
executionResults,
report,
};
}
}Step 3: 测试计划器 Prompt
<!-- src/prompts/planner.md -->
你是一个测试计划专家 Agent。
## 任务
根据用户提供的测试需求,制定详细的测试计划。
## 输入
- 需求描述:{{description}}
- 测试目标:{{target}}
## 输出要求
1. 列出所有需要测试的场景(至少 5 个)
2. 为每个场景编写测试步骤
3. 指定每个场景的预期结果
4. 标注优先级(P0/P1/P2)
## 输出格式
```json
{
"testCases": [
{
"id": "TC-001",
"title": "...",
"priority": "P0",
"steps": ["...", "..."],
"expectedResult": "..."
}
]
}
### Step 4: 执行器
```typescript
// src/agent/executor.ts
class Executor {
async execute(testCases: TestCase[]): Promise<ExecutionResult[]> {
const results: ExecutionResult[] = [];
for (const tc of testCases) {
console.log(` ⚡ 执行: ${tc.title}`);
try {
const startTime = Date.now();
// 逐步骤执行
for (const step of tc.steps) {
await this.executeStep(step);
}
const duration = Date.now() - startTime;
results.push({
testCaseId: tc.id,
status: 'passed',
duration,
screenshots: [],
});
console.log(` ✅ 通过: ${tc.title} (${duration}ms)`);
} catch (error) {
results.push({
testCaseId: tc.id,
status: 'failed',
error: (error as Error).message,
screenshots: [],
});
console.log(` ❌ 失败: ${tc.title}`);
}
}
return results;
}
}运行你的第一个 Agent
# 安装依赖
npm install
# 编译
npm run build
# 运行 Agent
npm start -- \
--description "测试百度搜索功能" \
--target "https://www.baidu.com"预期输出
🚀 开始执行测试任务: 测试百度搜索功能
📋 阶段 1/3: 制定测试计划...
生成了 8 个测试用例
🔄 阶段 2/3: 执行 8 个测试用例...
⚡ 执行: TC-001 打开百度首页
✅ 通过: TC-001 (1234ms)
⚡ 执行: TC-002 搜索关键词
✅ 通过: TC-002 (2345ms)
...
📊 阶段 3/3: 分析结果并生成报告...
总计: 8 | 通过: 7 | 失败: 1 | 通过率: 87.5%进阶方向
掌握了基础 Agent 后,可以往以下方向演进:
1. 多 Agent 协作
graph LR
Manager[管理 Agent] --> WebAgent[Web 测试 Agent]
Manager --> APIAgent[API 测试 Agent]
Manager --> PerfAgent[性能测试 Agent]
Manager --> SecAgent[安全测试 Agent]2. 持续学习
- 记录每次测试结果到知识库
- 从失败中学习常见错误模式
- 自动优化测试策略
3. CI/CD 集成
# .github/workflows/ai-test.yml
name: AI Testing Agent
on: [pull_request]
jobs:
ai-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm start -- --mode ci --target ${{ github.event.pull_request.html_url }}小结
本文我们从架构设计到代码实现,完整走了一遍 AI Testing Agent 的创建过程。核心要点:
- Agent = 编排器 + 计划器 + 执行器 + 分析器
- MCP 工具是 Agent 的手和脚——工具越丰富,Agent 能力越强
- 从简单开始,逐步迭代——先让 Agent 跑通一个场景,再扩展
- Prompt 质量决定 Agent 上限——花时间打磨每个组件的 Prompt
下一步建议:将本文的代码克隆到本地,替换为自己的测试场景,跑通之后再尝试扩展。