I'm working on the POST request to get a better understanding of RestAssured on the website https://reqres.in/
@Test
public void postTest() {
Response response = RestAssured.given()
.body("{\"name\": \"morpheus\"}"
"{\"job\": \"leader\"}")
.when()
.post(base_URI);
assertEquals(response.statusCode(), 201);
System.out.println(response.asPrettyString());
}
The status code
is 201
which is I expected, I want to print out the JSON data that I just POST by using response.asPrettyString()
But the data returned is
{
"id": "302",
"createdAt": "2022-08-23T21:47:44.857Z"
}
instad of
{
"name": "morpheus",
"job": "leader",
"id": "324",
"createdAt": "2022-08-23T21:47:21.176Z"
}
What should I do to get the full JSON data?
CodePudding user response:
Are you sure that isn't the full JSON data? Maybe the issue is your server?
I also noticed an issue in the JSON body. I would assume this is the payload you want to send?
{
"name": "morpheus",
"job": "leader"
}
I don't think there is anything wrong with your test code other than the JSON, but you can get restAssured to log the response payload and do the assertions...
@Test
public void postTest() {
RestAssured.given()
.body("{"
"\"name\": \"morpheus\","
"\"job\": \"leader\""
"}")
.when()
.post(base_URI)
.then().log().body()
.and().assertThat().statusCode(201);
}
CodePudding user response:
The problem is you forgot add content-type=application/json
to header. The correct code would be:
Response response = RestAssured.given()
.contentType(ContentType.JSON)
.body("{\n"
" \"name\": \"morpheus\",\n"
" \"job\": \"leader\"\n"
"}")
.when()
.post("https://reqres.in/api/users");
assertEquals(response.statusCode(), 201);
response.prettyPrint();
Result:
{
"name": "morpheus",
"job": "leader",
"id": "257",
"createdAt": "2022-08-24T02:48:40.444Z"
}