文章来源于霍格沃兹测试学院
1.需求背景
在实际的接口测试时,传参有时候可能需要很多,也可能我们就是想要一份完整的参数,必填项和非必填项都包含在内,比如下面的 json:
{ "store": { "book": [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 }, { "category": "fiction", "author": "Herman Melville", "title": "Moby Dick", "isbn": "0-553-21311-3", "price": 8.99 }, { "category": "fiction", "author": "J. R. R. Tolkien", "title": "The Lord of the Rings", "isbn": "0-395-19395-8", "price": 22.99 } ], "bicycle": { "color": "red", "price": 19.95 } }, "expensive": 10}
一个个在方法中传入显然不现实;写入hashmap中传入的话工作量和复杂度也很大,这个时候就需要一个模板,把我们需要的参数和结构提前定义好,我们只需要修改其中对应的值即可,这就要引出今天的两位主角:
- JsonPath
- Mustache
2.JsonPath
先来看第一个模板技术JsonPath,注意这里的JsonPath指的是Jayway JsonPath,maven依赖如下:
com.jayway.jsonpath json-path 2.4.0
2.1 元素定位
在UI自动化中我们会使用到xpath的元素定位的技术,在这里我将其类比过来方便理解记忆;Jayway JsonPath为我们提供了两种定位的写法:$.store.book[0].title、$['store']['book'][0]['title']
这里我习惯用第一种,也推荐使用,比较类似编程时的方法调用;
用 $ 表示从根元素开始找,. 点上要找的元素,一层一层的找下去,直到达到你需要找的地方;同样的元素可以根据中括号[]+索引的方法来区分,索引也是从0开始;