api-testing

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API 测试(中文版)

API Testing (Chinese Version)

英文版: 见技能
api-testing-en
提示词见本目录
prompts/api-testing.md
English Version: Refer to the skill
api-testing-en
.
Prompts can be found in
prompts/api-testing.md
in this directory.

何时使用

When to Use

  • 用户提到「API 测试」「api-testing」
  • 需要基于 Standard-version 执行该类测试或产出对应交付物
  • 触发示例:「根据以下内容生成/设计/编写…」
  • User mentions "API testing" or "api-testing"
  • Need to execute such tests or produce corresponding deliverables based on Standard-version
  • Trigger Example: "Generate/design/write... based on the following content"

输出格式选项

Output Format Options

默认 Markdown。若需 Excel / CSV / JSON,请在需求末尾说明,详见 output-formats.md
Default output is Markdown. If you need Excel / CSV / JSON, please specify it at the end of your request. For details, see output-formats.md.

如何使用

How to Use

  1. 打开本目录
    prompts/api-testing.md
    ,将虚线以下内容复制到 AI 对话。
  2. 附加你的具体需求。
  3. 若需 Excel/CSV/JSON,在末尾加上 output-formats.md 中的请求句。
  1. Open
    prompts/api-testing.md
    in this directory, copy the content below the dashed line to the AI conversation.
  2. Attach your specific requirements.
  3. If you need Excel/CSV/JSON, add the request sentence from output-formats.md at the end.

代码示例

Code Examples

1. Postman + Newman REST API 测试

1. Postman + Newman REST API Testing

完整的用户管理 API 测试示例,包含 10 个测试用例。
位置:
examples/postman-rest-api/
包含内容:
  • Postman 集合文件(10 个测试用例)
  • 环境变量配置
  • Newman 自动化运行脚本
  • 详细的 README 文档
快速开始:
bash
cd examples/postman-rest-api
npm install -g newman
./newman-run.sh
测试覆盖:
  • 用户 CRUD 操作(创建、读取、更新、删除)
  • 认证和授权测试
  • 错误处理和边界条件
  • 响应时间验证
  • 数据格式验证
详见:examples/postman-rest-api/README.md
Complete user management API testing example with 10 test cases.
Location:
examples/postman-rest-api/
Includes:
  • Postman collection file (10 test cases)
  • Environment variable configuration
  • Newman automation run script
  • Detailed README documentation
Quick Start:
bash
cd examples/postman-rest-api
npm install -g newman
./newman-run.sh
Test Coverage:
  • User CRUD operations (Create, Read, Update, Delete)
  • Authentication and authorization testing
  • Error handling and boundary conditions
  • Response time verification
  • Data format validation
For details: examples/postman-rest-api/README.md

最佳实践

Best Practices

API 测试设计原则

API Testing Design Principles

  1. 测试金字塔
    • 单元测试:测试单个 API 端点
    • 集成测试:测试多个端点的交互
    • 端到端测试:测试完整的业务流程
  2. 测试数据管理
    • 使用环境变量管理不同环境配置
    • 使用动态变量避免硬编码
    • 测试后清理数据
  3. 断言策略
    • 验证状态码
    • 验证响应结构(Schema Validation)
    • 验证响应数据
    • 验证响应时间
  4. 错误处理
    • 测试各种错误场景(4xx, 5xx)
    • 验证错误消息格式
    • 测试边界条件
  1. Test Pyramid
    • Unit testing: Test individual API endpoints
    • Integration testing: Test interactions between multiple endpoints
    • End-to-end testing: Test complete business processes
  2. Test Data Management
    • Use environment variables to manage configurations for different environments
    • Use dynamic variables to avoid hardcoding
    • Clean up data after testing
  3. Assertion Strategy
    • Verify status codes
    • Verify response structure (Schema Validation)
    • Verify response data
    • Verify response time
  4. Error Handling
    • Test various error scenarios (4xx, 5xx)
    • Verify error message format
    • Test boundary conditions

工具选择建议

Tool Selection Recommendations

工具适用场景优势
Postman/NewmanREST API 测试易用、可视化、CI/CD 集成
REST AssuredJava 项目强类型、BDD 风格
Pytest + RequestsPython 项目灵活、生态丰富
SuperTestNode.js 项目与 Express 集成好
GraphQL PlaygroundGraphQL API专为 GraphQL 设计
ToolApplicable ScenarioAdvantages
Postman/NewmanREST API testingEasy to use, visual, CI/CD integration
REST AssuredJava projectsStrongly typed, BDD style
Pytest + RequestsPython projectsFlexible, rich ecosystem
SuperTestNode.js projectsGood integration with Express
GraphQL PlaygroundGraphQL APIDesigned specifically for GraphQL

故障排除

Troubleshooting

常见问题

Common Issues

1. Newman 运行失败

1. Newman Run Failed

问题:
newman: command not found
解决方案:
bash
undefined
Problem:
newman: command not found
Solution:
bash
undefined

全局安装 Newman

Install Newman globally

npm install -g newman
npm install -g newman

或使用 npx(无需全局安装)

Or use npx (no global installation required)

npx newman run collection.json
undefined
npx newman run collection.json
undefined

2. 环境变量未生效

2. Environment Variables Not Taking Effect

问题: 测试中的变量显示为
{{variable}}
解决方案:
  • 确保使用
    -e
    参数指定环境文件
  • 检查环境文件中变量名是否正确
  • 在 Postman 中验证变量是否正确设置
bash
newman run collection.json -e environment.json
Problem: Variables in tests display as
{{variable}}
Solution:
  • Ensure the
    -e
    parameter is used to specify the environment file
  • Check if variable names in the environment file are correct
  • Verify variable settings in Postman
bash
newman run collection.json -e environment.json

3. 证书验证错误

3. Certificate Verification Error

问题:
SSL certificate problem
解决方案:
bash
undefined
Problem:
SSL certificate problem
Solution:
bash
undefined

开发环境可临时禁用 SSL 验证(不推荐生产环境)

Temporarily disable SSL verification in development environments (not recommended for production)

newman run collection.json --insecure
newman run collection.json --insecure

或指定 CA 证书

Or specify CA certificate

newman run collection.json --ssl-client-cert-list cert-list.json
undefined
newman run collection.json --ssl-client-cert-list cert-list.json
undefined

4. 请求超时

4. Request Timeout

问题:
Error: ETIMEDOUT
Error: ESOCKETTIMEDOUT
解决方案:
bash
undefined
Problem:
Error: ETIMEDOUT
or
Error: ESOCKETTIMEDOUT
Solution:
bash
undefined

增加超时时间(毫秒)

Increase timeout (in milliseconds)

newman run collection.json --timeout-request 30000
newman run collection.json --timeout-request 30000

添加请求延迟

Add request delay

newman run collection.json --delay-request 500
undefined
newman run collection.json --delay-request 500
undefined

5. 响应数据格式不匹配

5. Response Data Format Mismatch

问题: JSON Schema 验证失败
解决方案:
  • 使用 Postman 的 Schema 生成功能
  • 检查 API 文档确认数据结构
  • 使用
    pm.response.json()
    打印实际响应
javascript
// 在 Tests 中添加调试信息
console.log(pm.response.json());
Problem: JSON Schema validation failed
Solution:
  • Use Postman's Schema generation feature
  • Check API documentation to confirm data structure
  • Use
    pm.response.json()
    to print the actual response
javascript
// Add debugging information in Tests
console.log(pm.response.json());

6. 动态数据依赖问题

6. Dynamic Data Dependency Issue

问题: 后续请求依赖前一个请求的数据
解决方案:
javascript
// 在第一个请求的 Tests 中保存数据
pm.environment.set("userId", pm.response.json().id);

// 在后续请求中使用
// URL: {{baseUrl}}/users/{{userId}}
Problem: Subsequent requests depend on data from previous requests
Solution:
javascript
// Save data in Tests of the first request
pm.environment.set("userId", pm.response.json().id);

// Use it in subsequent requests
// URL: {{baseUrl}}/users/{{userId}}

7. 批量运行测试失败

7. Batch Test Run Failed

问题: 单个测试通过,批量运行失败
解决方案:
  • 检查测试之间的数据依赖
  • 确保每个测试独立可运行
  • 添加适当的延迟:
    --delay-request 200
  • 使用
    --bail
    在首次失败时停止
Problem: Individual tests pass, but batch run fails
Solution:
  • Check data dependencies between tests
  • Ensure each test can run independently
  • Add appropriate delay:
    --delay-request 200
  • Use
    --bail
    to stop on first failure

参考文件

Reference Files

  • prompts/api-testing.md — API 测试 Standard-version 提示词
  • output-formats.md — Markdown / Excel / CSV / JSON 请求说明
  • examples/postman-rest-api/ — Postman + Newman 完整示例
  • quick-start.md — 5 分钟快速上手指南
  • prompts/api-testing.md — Standard-version prompts for API testing
  • output-formats.md — Instructions for requesting Markdown / Excel / CSV / JSON output
  • examples/postman-rest-api/ — Complete Postman + Newman example
  • quick-start.md — 5-minute quick start guide