Newman 命令

安装与基础运行

npm install -g newman newman run collection.json newman run collection.json -e environment.json newman run collection.json \ -e staging.environment.json \ -g globals.json newman run collection.json \ --env-var "apiUrl=https://api.staging.example.com" \ --env-var "authToken=mytoken123"

报告器

newman run collection.json --reporters cli newman run collection.json --reporters junit newman run collection.json --reporters cli,junit,json \ --reporter-junit-export results/junit.xml \ --reporter-json-export results/report.json # 安装 htmlextra 报告器 npm install newman-reporter-htmlextra newman run collection.json \ --reporters htmlextra \ --reporter-htmlextra-export results/report.html \ --reporter-htmlextra-title "API 测试报告"

迭代数据与多次运行

# data.csv # username,password,expectedStatus # alice,pass123,200 # bob,wrong,401 newman run collection.json \ -d data.csv \ -e environment.json \ --reporters cli,junit \ --reporter-junit-export results.xml

超时与延迟

newman run collection.json --timeout-request 5000 newman run collection.json --timeout-response 10000 newman run collection.json --delay-request 200 newman run collection.json --insecure newman run collection.json --folder "认证测试"

退出码与 CI 集成

# 退出码 # 0 — 所有测试通过 # 1 — 测试失败 # 2 — collection 或环境文件错误 newman run collection.json; echo "退出码: $?" # GitHub Actions # - name: 运行 API 测试 # run: | # newman run collection.json \ # -e ${{env.ENVIRONMENT}} \ # --reporters cli,junit \ # --reporter-junit-export results/results.xml

作为 Node 模块使用

const newman = require('newman'); newman.run({ collection: require('./collection.json'), environment: require('./environment.json'), reporters: ['cli', 'junit'], reporter: { junit: { export: './results/junit.xml' } }, delayRequest: 100, }, (err, summary) => { if (err) throw err; if (summary.run.failures.length) { console.error(`${summary.run.failures.length} 个测试失败`); process.exit(1); } console.log('所有测试通过!'); });