来啦老铁!!!

上期跟大家学习了postman工具的2大高级功能,有朋友一定会问了,上期介绍的2个postman高级应用,高级是高级,但还是半自动化,不够香啊,postman能不能做API自动化呀?
负责任的告诉您,能!今天他来了,他postman带着newman来了!!!

newman是啥?
newman是postman官方出品的Runner的命令行执行工具,是postman的亲儿子,它能够让用户使用命令行运行postman的API集合,运行API集合的方式也相对比较灵活,并且能够支持生成多种测试报告,包括HTML报告;
newman是一个npm模块,因此我们只能在Node.js编程环境下安装和使用,也就是说,您的电脑需要安装Node.js(Node.js是啥请自行脑补)。
我们继续使用上期文章中介绍时使用的2个API,并安装好Node.js v10以上版本:newman Demo

-
创建项目文件夹;
我们在电脑里建个空文件夹,比如叫newman-demo; -
创建npm项目;
进入newman-demo文件夹,在PowseShell窗口或cmd 命令行窗口下执行命令:
npm init
回车后,根据提示设置项目的基本信息,无特别要求可直接一直回车,直到退出项目建设指引,如:

到此,您会发现newman-demo文件夹内多了个package.json文件,这是npm项目的标识;
如何打开PowseShell窗口或cmd 命令行窗口?
在文件夹内打开PowseShell窗口(在文件夹内空白处,按住键盘Shift键,然后点击鼠标右键,在打开的菜单栏中选择“Open PowerShell window here”):



-
安装newman模块;
newman-demo文件夹下,在PowseShell窗口或cmd 命令行窗口下执行命令:
npm install newman --save-dev
需要全局安装的可使用命令:
npm install -g newman



-
在postman导出API集合到newman-demo文件夹下;
导出入口 1
导出入口 2
导出入口 3
导出
导出完成
-
运行API集合;
在newman-demo文件夹下运行以下命令:
npx newman run ./Demo.postman_collection.json

啊哈~翻车了???

不要慌,这是因为被测API走的是https协议的,请求时需要证书,当然我们可以在电脑的环境变量中,设置环境变量NODE_TLS_REJECT_UNAUTHORIZED,值为0,来忽略该证书要求;

注意:设置完环境变量后,需重启PowerShell窗口或cmd命令行窗口,如仍不行需注销电脑。
再运行一次:

-
测试报告举例(HTML 报告);
安装HTML报告模块,命令:
npm install newman-reporter-html --save-dev

再次运行项目:
npx newman run ./Demo.postman_collection.json -r html
或
npx newman run ./Demo.postman_collection.json -r cli,html
(-r表示需要输出报告,cli和html代表报告类型,cli是在运行窗口打出测试报告,html表示使用newman-reporter-html生成html报告)

查看一下项目目录,您会发现多了个newman文件夹,里头放的就是HTML报告:


项目小结
newman的介绍咱们点到为止,开卷有益,newman的其他应用,可参照:
https://www.npmjs.com/package/newman
或:
https://github.com/postmanlabs/newman
从上面的介绍我们可以看到,当测试人员在postman测试完API后,可以将postman中的API集合导出,然后配合newman通过命令行测试API集合们(可一次运行多个集合)。
我们可以将平常需要回归测试的API通过该方式,将API们脚本化,有了该脚本化方案,我们可以将该项目放到git上,然后结合Jenkins等CI/CD工具,做到真正的API自动化!您是不是也秒懂了?
newman优缺点分析
优点:
- 门槛极低,基本不需要编程能力;
- 手工转自动化十分快速,运行简单;
- postman亲儿子,google维护,可靠;
缺点:
- 仅支持Node.js语言;
- 限制较多,不适合做大型项目,如:
- newman运行的是postman中导出的测试集,测试过程中的动态数据/测试准备/测试断言都只能在postman中事先定义好, 而postman的动态数据/测试准备/测试断言都有一定的限制,不能满足所有测试场景的要求(如数据库交互);
- 当API有变动时,测试人员需要在postman中修改,然后再次导入到newman项目,工作量会比直接修改代码来的多。也可在newman中直接修改集合中的内容,而集合的内容为json格式,阅读和维护有一定的难度;
总结
newman适合:
- 小型API项目的自动化;
- 短期项目的API回归测试;
- 编码能力较弱的测试团队或初学者;
夜已深,咱们下期再见!

网友评论