Introduction
We have learned about different concepts for Rest assured in our different articles. In this article, we will learn about setting a default RequestSpecification. Also, we will see all about the Querying RequestSpecification in Rest Assured.
Setting A Default RequestSpecification In Rest Assured
In Rest Assured, we can make multiple Request Specification as per our requirements. Rest Assured provides a way to set the default Request Specification so that we can send each request if no other Request Specification is set. In Java, the default value of an int data type is zero. Similarly, we can fix a Request Specification as default in Rest Assured.
For setting a default RequestSpecification in Rest Assured, we have to use the static property “requestSpecification“of RestAssured class. When no other RequestSpecification is set to request, default RequestSpecification is sent. If we are setting another request specification to the request, the default request specification will be overridden by the new one.
Rest Assured Program
package javaPackageName;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
public class RARequestSpecificationSettingDefault {
@BeforeClass
public void SetupDefault()
{
/*Using given() to create Request Specification*/
RequestSpecification objreq1= RestAssured.given();
/*Base URI*/
objreq1.baseUri("https://reqres.in/api/users");
/*Base Path*/
objreq1.basePath("/2");
RestAssured.requestSpecification = objreq1;
}
@Test
public void UseDefault()
{
/*Use default RequestSpecification*/
Response res = RestAssured.when().get();
System.out.println("Response for default: "+res.asString());
}
@Test
public void OverrideDefault()
{
/*Using with() to create request specification*/
RequestSpecification objreq2= RestAssured.with();
/*Base URI*/
objreq2.baseUri("https://reqres.in/api");
/*Base Path*/
objreq2.basePath("/users?page=3");
/*Override default Request Specification*/
Response res = RestAssured.given().spec(objreq2).get();
System.out.println("Response for overriding: "+res.asString());
}
}
Output: