5月29日 22:48
如何用 cURL 编写 API 自动化测试脚本?
cURL 测试脚本 = cURL 命令 + shell 判断 + 状态码/响应体验证。核心模式:curl -s -o /dev/null -w "%{http_code}" URL 拿状态码;curl -s URL | jq .field 提取响应体字段;for/while 循环批量测试。进阶:--fail 返回非零表示 HTTP 错误、--max-time 10 超时控制、--retry 3 重试。
追问
cURL 和 Postman 做测试哪个好?
cURL 适合 CI/CD 管道和脚本化——轻量、无 GUI 依赖、易版本控制。Postman 适合手动探索和团队协作。生产环境两者结合:开发用 Postman 调试,CI 用 cURL 验证。
怎么验证响应体内容?
curl -s URL | jq -e .status==200,-e 让 jq 在结果为 false 时返回 exit code 1。多字段验证:jq -e ".status==200 and .data.id != null"。
如何做性能基准测试?
curl -s -w "time_total: %{time_total}s\n" -o /dev/null URL。批量测用循环+awk 算平均值。注意 cURL 不含 DNS 缓存预热,首次请求偏慢。
怎么处理需要登录的接口?
先 curl 登录拿 token:TOKEN=$(curl -s -X POST login-url -d user/pass | jq -r .token),后续带 -H "Authorization: Bearer $TOKEN"。
cURL 脚本的缺点?
无测试报告、无并行执行、错误定位不友好。超过 20 个接口建议上专用测试框架(pytest+requests/Jest+supertest),cURL 适合轻量级冒烟测试和 CI 快速验证。