java - RestAssured:验证实体的创建
问题描述
我发布简单的数据,例如
{
"title" : "test Title"
}
到(让它成为)/posts uri,例如 smth like
RestAssured.baseURI = "http://localhost";
RestAssured.basePath = "/posts";
given()
.contentType("application/json")
.body("{\n" +
" \"title\": \"test Title\"\n" +
"}")
.when()
.post("")
.then().statusCode(201)
// .and(Verify that post created);
}
我可以验证,那个身体不是空的
.body(notNullValue())
或检查,响应的字段具有我们正在设置的值,例如
.body("title", equalTo("test Title"))
但我不确定,它的最佳/正确方式。所以,问题:如何验证,该实体是在发布后创建的,并带有restAssured?
解决方案
您可以使用 jsonPath 验证响应内容以确保其正确。下面是获取请求的响应,但您可以通过一些修改来使用它
import io.restassured.http.ContentType;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
Response response=given().contentType(ContentType.JSON).get("http://localhost:3000/posts");
//we need to convert response as a String and give array index
JsonPath jsonPath = new JsonPath(response.asString());
String title = jsonPath.getString("title");
// use index if response returns an array
String author=jsonPath.getString("author[2]");
// if it's int
int user_id = jsonPath.getInt("user_id");
System.out.println("title is "+title+" customerName is "+author);
推荐阅读
- excel - INDEX/MATCH 近似匹配,无需排序
- reactjs - 向 Express 和 Mongo DB 提出请求
- r - 如何有效地计算加权比例和置信区间?
- ruby-on-rails - 计算使用活动存储显示的视频的观看次数
- latex - 如何将里面的文字加粗|| || 在乳胶中?
- r - 如何组合两个绘图对象(非ggplot)
- java - JavaFX如何在TextField中聚焦时将键盘语言设置为阿拉伯语
- hadoop - 转储文件时,Pig Queries 卡在 0% Mapreduce Launcher 上?
- armeria - 如何使用 thrift 协议获取 httpservice 中的标头
- python - 为什么即使数组不是黑色,保存时图像也是黑色的?