In the previous blog, we covered the basic terminology that we will be using during rest assured testing. We also learned how to setup Rest Assured JAR or maven dependency in our project.
Rest Assured supports all the HTTP methods like GET, POST, PUT and DELETE. Here GET stands for Read operation, POST stands for Write operation, PUT stands for Update operation and DELETE stands for Delete operation.
Once you have the import of REST Assured set up, add the following static imports to your test class:
import static io.restassured.RestAssured.;
import static org.hamcrest.Matchers.;
Now let's look at an example of POST Request using Rest Assured
1.Set URI:
First we need to set the base uri of our api.. The base url without the resource is represented by uri. In our case, the full url is http://localhost:3000/comments, and the uri is http://localhost:3000/, with comment as the rescue name.
2. Call post method
In the post method, we begin with the Given method and specify the data to be added as a String in the body method. We simply add a check ‘contentType(ContentType.JSON)‘ to make sure that the response we get is in JSON format and under POST method we specify the path '/comment'
3.Validate Response Code
Validating http status code of the response is quite easy using Rest Assured. The method statusCode() takes an integer as input and validate against the response code. If the status code is not matching with the actual one, then the test case will fail. Any validation we want to perform can be written after .then().
4.Rest Assured – Validate Response Content
Validating response content from the JSON response is quite easy using rest assured. Check below the way we are validating the comment from the JSON response.
Here the function body takes 2 parameters. First one is the path to the field which we want to validate. In this case, it is the comment. Here we are using org.hamcrest.CoreMatchers.equalTo() method as well to compare the content against expected response. Also notice that we have combined the status code validation and response body validation together.
5. Number Validation Using Rest Assured
We can use the same equalTo method to validate numbers as long as they are integers.
Top comments (0)