前面两个章节 [Postman 实用接口测试系列 1 - 基础] 和 [Postman 实用接口测试系列 2 - 接口依赖] 咱们介绍了postman的具体使用和如何处理接口依赖。今天要介绍的是若是写测试用例。 这一部分就和咱们测试童鞋更息息相关了。json
大纲: * 测试用例编写的3A原则 * 脚本类型 * 如何编写脚本
接口测试简单的说就是建立一个请求,发送请求,而后判断请求的结果是不是指望的。数组
对于测试用例的编写能够参考3A原则:异步
对应的postman的模块以下图:post
咱们接下来的就会分别讲解这个几个模块的内容。测试
pre-request和test脚本有三种类型:spa
对于pre-request和test脚本执行顺序都是: collection > folder > request, 以下图debug
固然若是你只有一个请求,pre-request 和 test脚本都在这个请求上,那它的顺序就简单多了。3d
不一样层级的脚本,能够实现脚本的复用,好比同一个collection下的脚本,咱们都有一个共同的test是判断返回结果是200,那这个test就能够写在collection的脚本里。而后request只须要写本身特殊的test。
首先使用的语言是Javascript,咱们在脚本中可使用的几个主要模块有。code
pm.response
: 能够得到返回的结果pm.test
定义测试用例,用例名字,方法,方法返回一个 true/false 的布尔值,来判断用例pass仍是fail。pm.expect
来作断言//数组 pm.expect([1, 2, 3]).to.include(2); //json pm.expect({a: 1, b: 2, c: 3}).to.include({a: 1, b: 2}); //先判断类型更好 pm.expect([1, 2, 3]).to.be.an('array').that.includes(2); //判断返回的response body 是否含有某个字符串 pm.expect(pm.response.text()).to.include("string_you_want_to_search"); //判断是否含有子串 pm.expect('foobar').to.have.string('bar'); //判断是否包含某个jsonBody pm.response.to.have.jsonBody(""); //判断是否不包含某个jsonBody pm.response.to.not.have.jsonBody("error");
//判断环境 pm.expect(pm.environment.get("env")).to.equal("production"); //判断返回的response body 是否等于某个字符串 pm.response.to.have.body("response_body_string"); //判断返回的json内容 var jsonData = pm.response.json(); pm.expect(jsonData.value).to.eql(100); //判断两个数组里元素是否相同 pm.expect([1, 2, 3]).to.have.members([2, 1, 3]); //判断返回状态码是不是201,202中一个 pm.expect(pm.response.code).to.be.oneOf([201,202]);
expect([]).to.be.empty pm.expect('').to.be.empty; //先判断类型,而后判断是否为空 pm.expect([]).to.be.an('array').that.is.empty;
//判断类型是不是string,object或者undefined pm.expect('Postman').to.be.a('string'); pm.expect({a: 1}).to.be.an('object'); pm.expect(undefined).to.be.an('undefined');
//判断响应时长是否低于200ms pm.expect(pm.response.responseTime).to.be.below(200); //判断长度 pm.expect('foo').to.have.lengthOf(3); //判断个数 pm.expect([1, 2, 3]).to.have.lengthOf(2); //判断response pm.response.to.not.be.error; pm.response.to.be.ok; pm.response.to.be.withBody; pm.response.to.be.json; //判断Content-Type是否出现 pm.response.to.have.header("Content-Type"); //判断返回状态码是不是200 pm.response.to.have.status(200); //返回状态码是否含有某个字符串 pm.response.to.have.status("Created") //把xml body转成JSON var jsonObject = xml2Json(responseBody); //发送异步请求 pm.sendRequest("https://postman-echo.com/get", function (err, response) { console.log(response.json()); });
//是否含有集合里的全部的key pm.expect({a: 1, b: 2}).to.have.all.keys('a', 'b'); //是否含有一个集合中的某个key pm.expect({a: 1, b: 2}).to.have.any.keys('a', 'b'); //是否不含集合中的任何key pm.expect({a: 1, b: 2}).to.not.have.any.keys('c', 'd'); //先判断类型,再判断keys pm.expect({a: 1, b: 2}).to.be.an('object').that.has.all.keys('a', 'b');
小技巧,通常在作断言以前先使用.a先来判断类型效果更好
咱们这里写一个简单的单个请求的Test。判断返回状态码是不是200,某个参数的值是不是对的xml