【问题标题】:Verify values in Json Object using Rest Assured使用 Rest Assured 验证 Json 对象中的值
【发布时间】:2020-04-14 18:39:48
【问题描述】:

我想验证 id: 1 属于 Tiger Nixon

{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""}

我一直在关注这个文档:https://github.com/rest-assured/rest-assured/wiki/Usage#json-using-jsonpath,本栏目body("shopping.category.find { it.@type == 'groceries' }.item", hasItems("Chocolate", "Coffee"));

目前我得到一个空指针异常。我可以使用一些帮助来提出解决方案。提前感谢您的宝贵时间。

import com.google.gson.JsonObject;
import io.restassured.RestAssured;
import org.testng.Assert;

public class RestAssuredExample_2 {

    public void getResponse() {
        JsonObject responseObject = RestAssured.get("http://dummy.restapiexample.com/api/v1/employees")
                .then()
                .extract().response().as(JsonObject.class);

        String emp1Name = responseObject.get("data.find{it.@id=='1'}.employee_name").toString();
        Assert.assertEquals(emp1Name, "Tiger Nixon");
    }

    public static void main(String[] args) {
        RestAssuredExample_2 rest2 = new RestAssuredExample_2();
        rest2.getResponse();
    }
}  

错误:

Exception in thread "main" java.lang.NullPointerException
    at HTTPz.RestAssuredExample_2.getResponse(RestAssuredExample_2.java:16)

【问题讨论】:

    标签: java json rest-assured


    【解决方案1】:

    试图复制这个场景

    String responseObject = RestAssured.get("http://dummy.restapiexample.com/api/v1/employees").then().extract().asString();
    JsonPath js = new JsonPath(responseObject);
    String emp1Name = js.get("data.find {it.id =='1'}.employee_name").toString();
    System.out.println(emp1Name);
    

    我将 emp1Name 的值设为“Tiger Nixon

    区别:

    原文:it.@id=='1'

    我的: it.id =='1'

    似乎@ 是用于 XMLPath 而不是用于 JSONPath,老实说我也不会详细了解它,因为我只使用 JSONPath 很长时间了 :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多