Postman Linux版实现持续集成的步骤指南
在Linux系统(如Ubuntu)上,需提前安装以下工具:
安装命令示例(以Ubuntu为例):
# 安装Git
sudo apt update && sudo apt install -y git
# 安装Node.js & npm(使用NodeSource仓库)
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs
# 验证安装
node -v && npm -v
# 安装Newman(全局)
sudo npm install -g newman
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);
});
pm.test("Response contains expected data", function () {
const jsonData = pm.response.json();
pm.expect(jsonData.key).to.eql("expectedValue");
});
api_collection.json),并存入版本控制的代码仓库(如GitHub、GitLab)。# 添加Jenkins仓库密钥
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
# 添加Jenkins仓库
sudo sh -c 'echo deb http://pkg.jenkins.io/debian-stable binary/ /etc/apt/sources.list.d/jenkins.list'
# 安装Jenkins
sudo apt update && sudo apt install -y jenkins
# 启动Jenkins服务
sudo systemctl start jenkins
sudo systemctl enable jenkins
进入Jenkins Web界面(http://<服务器IP>:8080),通过「Manage Jenkins」→「Manage Plugins」安装以下插件:
创建run-collection.sh脚本,封装Newman命令,实现自动安装Newman、运行测试、生成JUnit报告:
#!/bin/bash
# 安装Newman(确保npm可用)
npm install -g newman
# 运行Postman集合,生成JUnit格式报告
newman run "api_collection.json" \
--reporters cli,junit \
--reporter-junit-export "report.xml"
# 检查测试结果,失败则退出
if [ $? -ne 0 ]; then
echo "Some tests failed!"
exit 1
else
echo "All tests passed!"
fi
赋予脚本执行权限:
chmod +x run-collection.sh
进入Jenkins →「New Item」→ 输入任务名称(如Postman-API-Tests)→ 选择「Pipeline」→ 点击「OK」。
main);Jenkinsfile(后续创建)。在代码仓库根目录创建Jenkinsfile,定义流水线流程(Checkout代码→运行测试→发布结果):
pipeline {
agent any
stages {
stage('Checkout') {
steps {
git branch: 'main', url: 'https://github.com/your-username/your-repo.git'
}
}
stage('Run Postman Tests') {
steps {
sh './run-collection.sh' // 调用Shell脚本运行测试
}
}
stage('Publish Test Results') {
steps {
junit 'report.xml' // 解析JUnit报告(需脚本生成)
}
}
}
post {
always {
echo 'Pipeline completed!'
}
failure {
emailext body: 'Postman tests failed!',
subject: 'CI/CD Pipeline Failed',
to: 'dev-team@example.com' // 发送失败通知(需配置邮件插件)
}
}
}
run-collection.sh和Jenkinsfile提交到代码仓库的main分支;base_url),导出为environment.json,并在Newman命令中指定(--environment environment.json),以支持不同环境(开发、测试、生产)的测试;--parallel选项,加速大规模测试集的执行。通过以上步骤,即可在Linux系统上实现Postman与CI/CD工具的无缝集成,实现API测试的自动化执行与持续集成。