放心:验证实体的创建



我发布简单的数据,例如

{
"title" : "test Title"
}

到(顺其自然(/帖子 URI,例如 smth 喜欢

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"))

但我不确定,它的最佳/正确方式。 那么,问题:如何验证该实体是在发布后创建的,并放心?

您可以使用 jsonPath 验证响应内容以确保其正确无误。下面是对 get 请求的响应,但您可以将其与一些修改一起使用

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);

最新更新