霍格沃兹测试开发

JSON 响应断言

霍格沃兹测试开发学社

ceshiren.com

JSON 简介

  • 是 JavaScript Object Notation 的缩写

  • 是一种轻量级的数据交换格式

  • 是理想的接口数据交换语言

官网:https://www.json.org/json-en.html

JSON 与接口的关系

JSON 响应数据

  • 如何获取 headers 中 Hello 的值?
{
  "args": {},
  "headers": {
    "Accept": "*/*",
    "Accept-Encoding": "gzip,deflate",
    "Hello": "Hogwarts",
    "Host": "httpbin.ceshiren.com",
    "User-Agent": "Apache-HttpClient/4.5.13 (Java/11.0.13)",
    "X-Forwarded-Host": "httpbin.ceshiren.com",
    "X-Scheme": "https"
  },
  "origin": "113.89.246.226",
  "url": "https://httpbin.ceshiren.com/get"
}

JSONPath 简介

  • 是一种查询语言
  • 是用来解析 JSON 数据

项目地址:https://github.com/json-path/JsonPath

JSONPath 语法

JSONPath 描述
$ 根节点
@ 现行节点
.. 不管位置,选择所有符合条件的元素
* 匹配所有元素节点
. 取子节点
[] 取子节点,支持名称或者下标
[,] 支持迭代器中做多选
?() 支持过滤操作

JSONPath 语法示例

  • 使用点号
    • $.address.city
    • $.phoneNumbers[0].number
    • $.phoneNumbers[*].number
    • $..number
  • 使用中括号
    • $[address][city]
    • $[phoneNumbers][0][number]
  • 过滤条件
    • $.phoneNumbers[?(@.type == 'iPhone')].number

JSONPath 响应断言

  • REST assured 内置解析方法
  • 第三方 json-path解析方法

JSONPath 响应断言

  • 内置解析方法
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static io.restassured.path.json.JsonPath.from;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestJSONPathNested {

    @Test
    void fun() {

        // 获取响应信息,并转成字符串对象
        String resp = given()
                .header("Hello", "Hogwarts")
                .when()
                .get("https://httpbin.ceshiren.com/get")
                .then()
                .log().body()
                .extract().response().asString();

        // 使用JSONPath解析响应体
        String word = from(resp).getString("headers.Hello");
        System.out.println(word);

        // 响应断言
        assertEquals("Hogwarts", word);

    }
}

JSONPath 响应断言

  • 第三方解析方法
package ch06;

import com.jayway.jsonpath.JsonPath;
import org.junit.jupiter.api.Test;

import static io.restassured.RestAssured.given;
import static org.junit.jupiter.api.Assertions.assertEquals;

public class TestJSONPathStandalone {

    @Test
    void fun() {

        // 获取响应信息,并转成字符串对象
        String resp = given()
                .header("Hello", "Hogwarts")
                .when()
                .get("https://httpbin.ceshiren.com/get")
                .then()
                .extract().response().asString();

        // 使用JSONPath解析响应体
        String word = JsonPath.read(resp, "$.headers.Hello");
        System.out.println(word);

        // 响应断言
        assertEquals("Hogwarts", word);

    }
}

附录:JSONPath 依赖配置

  • pom.xml中添加配置信息
  • 注意来源是 com.jayway.jsonpath
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.6.0</version>
    <scope>test</scope>
</dependency>