关于postman:Postman-实用接口测试系列-7-在prerequest-script里发送请求

50次阅读

共计 1840 个字符,预计需要花费 5 分钟才能阅读完成。

在执行接口测试之前,咱们须要在 pre-request 脚本里执行一些接口申请做一些筹备工作,比方要删除某个订单,则须要确认在删除之前这个订单是存在的,那咱们就能够在 pre-request 里判断是否存在订单,不存在则创立一个订单。

咱们由浅入深的由几个例子来阐明如何应用。

1. 发送一个简略的 get 申请

pm.sendRequest("https://postman-echo.com/get", function (err, response) {console.log(response.json());
});

2. 发送一个制订 headers 的 get 申请

pm.sendRequest({
    url: "https://postman-echo.com/get",
    method: "GET",
    header: {
        "Host": "postman-echo.com",
        "Accept-Encoding": "gzip, deflate, b"
    }
}, function (err, response) {console.log(response.json())
});

3. get 申请里的内容应用变量

pm.sendRequest({url: "https:" + pm.environment.get("host") + "/get",
    method: "GET",
    header: {
        "Host": "postman-echo.com",
        "Accept-Encoding": "gzip, deflate, b"
    }
}, function (err, response) {console.log(response.json())
});

4. 满足某个条件后发送第二个 get 申请(接口同步)

pm.sendRequest({
    url: "https://postman-echo.com/get",
    method: "GET",
    header: {
        "Host": "postman-echo.com",
        "Accept-Encoding": "gzip, deflate, b"
    },
}, function (err, response) {console.log(response.json())
    
    //if response not empty, then call request again
    if(response.json()!={}){
        pm.sendRequest({
            url: "https://postman-echo.com/get",
            method: "GET",
            header: {
                "Host": "postman-echo.com",
                "Accept-Encoding": "gzip, deflate, b"
            }
        }, function (err, response) {console.log(response.json())
        });

    }
});

5. 发送 post 申请

pm.sendRequest({
    url: "https://postman-echo.com/post",
    method: "POST",
    header:'headername1:value1',
    body: {foo: 'thisisfoovalue'}
}, function (err, response) {console.log(response.json())
});

有时候发现 body 传不过来,能够尝试应用 mode ‘raw’, 如下图:

pm.sendRequest({
    url: "https://postman-echo.com/post",
    method: "POST",
    header:'headername1:value1',
    body: {
        mode: 'raw',
        raw: JSON.stringify({foo: 'thisisfoovalue'})
    }
}, function (err, response) {console.log(response.json())
});

也能够尝试把申请的内容独自拿进去定义:

const echoPostRequest = {
    url: 'https://postman-echo.com/post',
    method: 'POST',
    header: 'headername1:value1',
    body: {
      mode: 'raw',
      raw: JSON.stringify({foo: 'thisisfoovalue'})
    }
  };
  
  pm.sendRequest(echoPostRequest, function (err, res) {console.log(err ? err : res.json());
  });

正文完
 0