首页 > 解决方案 > 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?

标签: javajsonrest-assured

解决方案


您可以使用 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);

推荐阅读