跳到主要内容

安装和运行 Newman

要开始使用 Newman,请安装 Node.js,然后安装 Newman。然后你可以运行你的集合。

安装 Newman

  1. Newman 建立在 Node.js 之上。要运行 Newman,请确保安装了 Node.js。按照步骤为你的 CI 平台 下载 Node 。 (请注意,某些 CI 系统具有预安装 Node 的配置。)确保你使用的是 Node.js v4 或更高版本。
  2. 从 npm 全局安装 Newman 在你的系统上,这样你就可以从任何地方运行它:

跑步 Newman

运行 Newman 的最简单方法是使用集合运行它。你可以从你的文件系统运行任何收集文件。

你可以 导出集合 以作为文件共享。

$ newman run mycollection.json

你还可以通过 共享 将集合作为 URL 传递。

你的收藏可能使用了环境变量。要提供一组随附的 环境变量 ,请从 Postman 导出模板并使用-e标志运行它们。

$ newman run https://www.postman.com/collections/cb208e7e64056f5294e5 -e dev_environment.json

测试失败的示例集合

→ Status Code Test
GET https://postman-echo.com/status/404 [404 Not Found, 534B, 1551ms]
1\. response code is 200

┌─────────────────────────┬──────────┬──────────┐
│ │ executed │ failed │
├─────────────────────────┼──────────┼──────────┤
│ iterations │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ requests │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ test-scripts │ 1 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ prerequest-scripts │ 0 │ 0 │
├─────────────────────────┼──────────┼──────────┤
│ assertions │ 1 │ 1 │
├─────────────────────────┴──────────┴──────────┤
│ total run duration: 1917ms │
├───────────────────────────────────────────────┤
│ total data received: 14B (approx) │
├───────────────────────────────────────────────┤
│ average response time: 1411ms │
└───────────────────────────────────────────────┘

# failure detail

1\. AssertionFai… response code is 200
at assertion:1 in test-script
inside "Status Code Test" of "Example Collection with
Failing Tests"

所有测试和请求的结果都可以导出到一个文件中。使用 JSON 报告器和文件名将输出保存到文件中。

$ newman run mycollection.json --reporters cli,json --reporter-json-export outputfile.json

Newman 允许你使用 Postman support 的所有 库和对象 来运行测试和预请求脚本。

选项

Newman 提供了一组丰富的选项来自定义运行。在 Newman options 了解更多信息

将 Newman 与 CI/CD 结合使用

默认情况下,如果一切按预期运行且没有异常,Newman 将以状态代码 0 退出。你可以配置持续集成 (CI) 工具以响应 Newman 的退出代码并相应地通过或失败构建。如果遇到状态代码为 1 的测试用例错误,你还可以使用该--bail标志让 Newman 停止运行,然后你的 CI 工具或构建系统可以拾取该错误。

使用 Newman 作为 Node.js 库

Newman 是从头开始建造的图书馆。它可以以各种方式扩展和使用。你可以在 Node.js 代码中按如下方式使用它:

var newman = require('newman'); // require Newman in your project

// call newman.run to pass `options` object and wait for callback
newman.run({
collection: require('./sample-collection.json'),
reporters: 'cli'
}, function (err) {
if (err) { throw err; }
console.log('collection run complete!');
});