APIs and HTTP Client: Response Code Validation

In this article, we will validate the GET call response status code using the TestNG assertion

Prem Singh Rathore
3 min readAug 21, 2021
Image source: Google

👇 Check out the first part to generate the response 👇

We need to remove the information fetching block from Rest Client and paste it in the Get API Test class to validate it inside the Test case.

Rest Client

Paste it in the Get API Test class

Test case inside the class

Here, you can see the red line below the response object because it is not yet defined in the Test class.

Make sure your Get method inside the Rest Client returns the response to use it in the Get API Test class.

Get method inside Rest Client.

We need to define an object for the Get method in the Test class to store the response.

CloseableHttpResponse closeableHttpResponse;closeableHttpResponse = restClient.get(URL);

You can see how the error is gone.

Test class

Validating the response

We will define some status codes in the Base class.

public int RESPONSE_STATUS_CODE_200 = 200;public int RESPONSE_STATUS_CODE_201 = 201;public int RESPONSE_STATUS_CODE_400 = 400;public int RESPONSE_STATUS_CODE_401 = 401;public int RESPONSE_STATUS_CODE_500 = 500;public int RESPONSE_STATUS_CODE_502 = 502;

We will call these codes in our Test class.

Let’s put assertions now and validate the status code.

import org.testng.Assert;Assert.assertEquals(statusCode, RESPONSE_STATUS_CODE_200);

Make sure you import the TestNG assertion library.

Let’s run the code and see if it is working or not.

Console Window
Image credit: Wisdmlabs.com

Thanks for reading.

Here is the Git repo for you to download the code.

Declaration: This article is based on one of the videos by Naveen AutomationLabs and, the video link is below.

--

--