java - 使用 Rest Assured 验证 Json 对象中的值
问题描述
我想验证 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)
解决方案
试图复制这种情况
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 很长时间了 :)
推荐阅读
- javascript - Jest 不会转换 node_module 依赖项
- laravel - Livewire:绑定一个模型,前面可以看到所有字段吗?
- python - 需要帮助合并所有结果
- c# - :'不能在不可变对象实例上为'Fill.Color'设置动画。'
- google-sheets - 如何通过 Google Docs API 插入嵌入式工作表?
- mysql-workbench - MySQL工作台:多个窗口
- odoo-13 - 在销售订单中修改商品价格时的问题 (Odoo 13)
- python - Python 2D 数组列表索引必须是整数或切片,而不是元组
- javascript - TypeError:无法读取未定义的属性“类型” - Redux
- php - PHP curl API 请求有效。使用爆炸来制作数组,而不是提供所需的键值对