Response Specification in REST Assured

Profile picture for user devraj

Earlier we have discussed Request Specification, In this one we will discuss about Response Specification. There can be several common things in response as well, like status code, checking the response time. All the common validation can be put in Response Specification to avoid duplicate code. Even for several APIs response body could have some common values.

public class ResponseSpecificationTest 
{
	ResponseSpecBuilder resSpecBuilder;
	static ResponseSpecification responseSpec;
	
	@BeforeClass
	public void setup()
	{
		RestAssured.baseURI = "https://reqres.in/";
		RestAssured.basePath = "api";
		resSpecBuilder = new ResponseSpecBuilder();
		resSpecBuilder.expectStatusCode(200);
		resSpecBuilder.expectBody("ad.company", equalTo("StatusCode Weekly"));
		responseSpec = resSpecBuilder.build();
	}

	@Test(enabled=true)
	public void ArraySizeAndElements()
	{
		given()
			.queryParam("page", "2")
		.when()
			.get("/users/")
		.then()
			.spec(responseSpec)
			.body("total_pages", equalTo(2));	
	}
	
	@Test(enabled=true)
	public void reusedResponse()
	{
		given()
		.when()
			.get("/users/2")
		.then()
		.spec(responseSpec);	
	}
}

In above code you can see statuscode, company validation has been added to response builder. At the same time you can observe we have added method level validation separately inside body for total_pages.