自动化API测试:从Postman到完整测试流水线
立即解锁
发布时间: 2025-09-05 00:44:07 阅读量: 8 订阅数: 12 AIGC 

# 自动化API测试:从Postman到完整测试流水线
## 1. 在Postman中编写HTTP请求测试
我们可以使用URL `http://127.0.0.1:8000/v1/item/create/cooking` 创建 `2_create` 测试。以下是测试代码示例:
```javascript
var result = pm.response.json()
pm.test("response is ok", function () {
pm.response.to.have.status(200);
});
pm.test("returns two pending item", function(){
if (result["pending_items"].length !== 2){
throw new Error(
"returns the wrong number of pending items");
}
})
pm.test("Pending item has the correct title", function(){
if (result["pending_items"][0]["title"] !== "washing"){
throw new Error(
"title of the pending item is not 'washing'");
}
})
pm.test("Pending item has the correct status", function(){
if (result["pending_items"][0]["status"] !==
"PENDING"){
throw new Error(
"status of the pending item is not 'pending'");
}
})
pm.test("Pending item has the correct title", function(){
if (result["pending_items"][1]["title"] !== "cooking"){
throw new Error(
"title of the pending item is not 'cooking'");
}
})
pm.test("Pending item has the correct status", function(){
if (result["pending_items"][1]["status"] !==
"PENDING"){
throw new Error(
"status of the pending item is not 'pending'");
}
})
pm.test("returns zero done items", function(){
if (result["done_items"].length !== 0){
throw new Error(
"returns the wrong number of done items");
}
})
pm.test("checking pending item count", function(){
if (result["pending_item_count"].length === 1){
throw new Error(
"pending_item_count needs to be one");
}
})
pm.test("checking done item count", function(){
if (result["done_item_count"].length === 0){
throw new Error(
"done_item_count needs to be zero");
}
})
```
这些测试也直接适用于 `3_create` 测试,因为重复创建与 `2_create` 使用相同的URL。这些测试有一定的重复性,是练习基本Postman测试的好机会。你可以在以下URL的JSON文件中查看测试:[JSON文件链接](https://github.com/PacktPublishing/Rust-Web-Programming-2nd-Edition/blob/main/chapter09/building_test_pipeline/web_app/scripts/to_do_items.postman_collection.json)。
## 2. 使用Newman自动化Postman测试
手动运行所有测试可能很繁琐,我们可以使用Newman自动化运行和检查集合中的所有测试。步骤如下:
1. **导出Postman集合为JSON文件**:在Postman左侧导航栏中点击集合,然后点击灰色的“Export”按钮。
2. **检查导出的JSON文件结构**:
- 测试套件的头部定义如下:
```json
"info": {
"_postman_id": "bab28260-c096-49b9-81e6-b56fc5f60e9d",
"name": "to_do_items",
"schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
"_exporter_id": "3356974"
}
```
- 单个测试定义示例:
```json
"item": [
{
"name": "1_create",
"event": [
{
"listen": "test",
"script": {
"exec": [
"var result = pm.response.json()",
...
],
"type": "text/javascript"
}
}
],
"request": {
```
0
0
复制全文
相关推荐










