Validating GET, POST, PUT and DELETE responses in RestAssured
Mohith Nayak
SDET | Test Automation | Software Testing | Java | Information Security | performance testing
Rest Assured is a Java library used for testing RESTful APIs. It provides an easy-to-use API for creating and executing HTTP requests, and then validating the response returned by the server.
Validating response in Rest Assured:
a. Status Code: You can use the assertThat() method to verify the status code of the response. For example, assertThat().statusCode(200).
b. Response Body: You can use the assertThat() method to verify the response body of the response. For example, assertThat().body("name", equalTo("John Doe")).
c. Response Headers: You can use the assertThat() method to verify the headers of the response. For example, assertThat().header("Content-Type", equalTo("application/json")).
Validating GET response
@Test
public void testGetApi() {
Response response = given()
.when()
.get("/users/12345");
response.then().statusCode(200);
response.then().body("name", equalTo("John Doe"));
response.then().body("age", equalTo(30));
}
In this example, we're validating the status code, name, and age of the response received for the GET request.
Validating POST response:
@Test
public void testPostApi() {
Response response = given()
.body("{ \"name\": \"John Doe\", \"age\": 30 }")
.when()
.post("/users");
response.then().statusCode(201);
领英推荐
response.then().body("name", equalTo("John Doe"));
response.then().body("age", equalTo(30));
}
In this example, we're validating the status code, name, and age of the response received for the POST request.
Validating PUT request
@Test
public void testPutApi() {
Response response = given()
.body("{ \"name\": \"Jane Doe\", \"age\": 35 }")
.when()
.put("/users/12345");
response.then().statusCode(200);
response.then().body("name", equalTo("Jane Doe"));
response.then().body("age", equalTo(35));
}
In this example, we're validating the status code, name, and age of the response received for the PUT request.
Validating DELETE response
@Test
public void testDeleteApi() {
Response response = given()
.when()
.delete("/users/12345");
response.then().statusCode(204);
}
In this example, we're validating the status code of the response received for the DELETE request. Since the DELETE request typically does not return a response body, we don't need to validate the response body. Instead, we only need to validate the status code to ensure that the resource was deleted successfully.