1. 在Ubuntu上安装Postman
Postman支持多种方式在Ubuntu上安装,常见方法如下:
sudo snap install postman --classic,等待安装完成即可。wget -qO - https://dl.postman.co/postman.gpg | sudo apt-key add -;echo "deb https://dl.postman.co/debian $(lsb_release -cs) main" | sudo tee /etc/apt/sources.list.d/postman.list;sudo apt update && sudo apt install postman。sudo apt update && sudo apt install flatpak;再添加Flathub仓库:flatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepo;最后安装Postman:flatpak install flathub com.postman.Postman。2. 准备自动化测试的基础框架
// 检查状态码是否为200
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
// 检查响应体是否包含特定字段
pm.test("Response contains user ID", function () {
const jsonData = pm.response.json();
pm.expect(jsonData).to.have.property("id");
});
// 从环境变量获取token并设置请求头
const token = pm.environment.get("auth_token");
pm.request.headers.add({ key: "Authorization", value: `Bearer ${token}` });
base_url: https://api.example.com)。在请求中使用{{base_url}}引用变量,切换环境时变量值会自动替换。3. 运行自动化测试
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -→sudo apt install -y nodejs),再执行npm install -g newman安装Newman。导出集合为JSON文件(点击集合→“Export”→选择“Collection v2.1”),然后运行:newman run /path/to/collection.json --environment /path/to/environment.json。可通过--reporters cli,json生成报告,或集成到Jenkins、GitLab CI等工具中。4. 高级技巧提升测试效率
data.csv:userId,title\n1,Test User),在Collection Runner中勾选“Data”→选择文件。在脚本中使用pm.iterationData.get("userId")获取当前迭代数据,验证不同输入下的响应。.gitlab-ci.yml中添加:stages:
- test
run_postman_tests:
stage: test
script:
- npm install -g newman
- newman run /path/to/collection.json
实现代码提交后自动运行测试。