
什么是 REST API?
關鍵特性:
stage('Run Postman Tests') {
steps {
sh """
newman run api_tests.postman_collection.json \
-e environments/dev.json \
--reporters cli,junit,html \
--reporter-junit-export reports/junit.xml \
--reporter-html-export reports/report.html
"""
}
post {
always {
junit 'reports/junit.xml'
publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html'])
}
}
}
關鍵特性:
mvn test
即可觸發。given()
.baseUri("https://api.example.com/v1")
.auth().oauth2(token)
.when()
.get("/artists")
.then()
.statusCode(200)
.body("size()", greaterThan(0));
# Prism 啟動 Mock 服務
prism mock openapi.yaml --port 4010
src/
├── config/
│ └── env.properties
├── data/
│ └── artists.csv
├── lib/
│ ├── http_client.py
│ └── assertions.py
└── tests/
├── test_get_artists.py
└── test_create_artist.py
data.json
+ --iteration-data
實現多次執行;@pytest.mark.parametrize
傳入數據文件。--parallel
參數加速執行; < forkCount > 2C < /forkCount >
;pytest -n auto
實現多核并行。pipeline {
agent any
environment {
NODE_ENV = 'test'
COLLECTION = 'collections/api_tests.postman_collection.json'
ENV_FILE = 'environments/dev.json'
}
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Install Dependencies') {
steps { sh 'npm install -g newman' }
}
stage('API Mock') {
steps {
sh 'prism mock openapi.yaml --port 4010 &'
sh 'sleep 5'
}
}
stage('Run Tests') {
steps {
sh """
newman run $COLLECTION -e $ENV_FILE \
--reporters cli,junit,html \
--reporter-junit-export reports/junit.xml \
--reporter-html-export reports/report.html
"""
}
post {
always {
junit 'reports/junit.xml'
publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html'])
}
failure {
mail to: 'team@example.com',
subject: "?? API Tests Failed (#${env.BUILD_NUMBER})",
body: "請查看 Jenkins 構建報告:${env.BUILD_URL}"
}
}
}
}
}
stages:
- mock
- test
mock_service:
stage: mock
image: stoplight/prism
script:
- prism mock openapi.yaml --port 4010
tags:
- docker
api_test:
stage: test
image: node:18
dependencies:
- mock_service
script:
- npm install -g newman
- newman run collections/api_tests.postman_collection.json \
-e environments/dev.json \
--reporters cli,junit \
--reporter-junit-export reports/junit.xml
artifacts:
paths:
- reports/*.xml
when: always
k6 run --vus 100 --duration 30s script.js
通過本篇“API 自動化測試全攻略”,你將掌握API 自動化測試、CI/CD 集成、Mock 服務、性能與安全測試的全流程方案,幫助團隊實現高效持續交付與質量保障。立即動手,構建你的下一代 API 自動化測試體系!
原文引自YouTube視頻:https://www.youtube.com/watch?v=Un_xNV8h51c