Skip to main content

Rest Assured Assertions using TestNG

While automating APIs using REST Assured in several situations you find you need to assert the things outside of normal flow where you don't mention equalTo() inside .body().

In that case you can use TestNG or JUnit Assertions. There is nothing special things you need to do here you just need to receive the response in some variable or using some method and assert it.

TestNG Assertions in Rest Assured

In below example you can see I am using TestNG assert to validate one of the header and body key:

import org.testng.Assert;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;

import static io.restassured.RestAssured.given;

public class ReqRes 
{
    @BeforeClass
    public void setup()
    {
        RestAssured.baseURI = "https://reqres.in/";
        RestAssured.basePath = "api";
    }
	
    @Test(enabled=true)
    public void TestPathParametersExample()
    {
        Response res = given()
	        .queryParam("page", "2")
        .when()
        .get("/users/");
		
        JsonPath js = new JsonPath(res.asString());
		
        Assert.assertEquals(js.getString("total_pages"), "2");
        Assert.assertEquals(res.getHeader("server"), "cloudflare");		
	}
}

Submitted by tgoswami on September 2, 2020

Tarun has 11+ years of experience in Quality Assurance in different domains like Banking, E-commerce, Health and Education.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.