在 Ubuntu 上使用 Postman 进行自动化测试
一 安装与启动
sudo snap install postman --classicpostmanwget -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.listsudo apt update && sudo apt install postmansudo apt update && sudo apt install flatpakflatpak remote-add --if-not-exists flathub https://flathub.org/repo/flathub.flatpakrepoflatpak install flathub com.postman.Postmanwget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gzsudo tar -xzf postman.tar.gz -C /opt/sudo ln -s /opt/Postman/Postman /usr/local/bin/postmansudo nano /usr/share/applications/postman.desktop,内容示例:[Desktop Entry]
Encoding=UTF-8
Name=Postman
Exec=/opt/Postman/Postman
Icon=/opt/Postman/app/resources/app/assets/icon.png
Terminal=false
Type=Application
Categories=Development;
sudo chmod +x /usr/share/applications/postman.desktop
以上方式任选其一即可完成安装与启动。二 编写自动化测试脚本
// Pre-request Script
console.log("Pre-request running");
const token = pm.environment.get("token");
pm.request.headers.add({ key: "Authorization", value: "Bearer " + token });
// Tests
pm.test("Status code is 200", () => pm.response.to.have.status(200));
pm.test("Response time < 200ms", () => pm.expect(pm.response.responseTime).to.be.below(200));
pm.test("Response has id", () => {
const json = pm.response.json();
pm.expect(json.id).to.be.a("number");
});
pm.environment.get/set 读取与写入;结合数据文件可实现参数化测试。三 在桌面客户端运行自动化测试
console.log 信息,结合脚本错误提示进行调试,快速定位问题。四 在 CI/CD 中使用 Newman 运行测试
npm install -g newman# 基本运行
newman run your_collection.json
# 使用环境变量
newman run your_collection.json --environment your_env.json
# 生成报告(CLI + JUnit)
newman run your_collection.json --reporters cli,junit --reporter-junit-export report.xml
name: Run Postman API Tests
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
postman-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 18
- run: npm install -g newman
- run: newman run "your_postman_collection.json" --reporters cli,junit --reporter-junit-export report.xml