REST Assured 系列汇总 之 REST Assured 17 - 设置默认的RequestSpecification
我们可以根据需要创建多个Request Specification,Rest Assured提供一种方式设置一个默认的Request Specification,所以这个默认的Request Specification可以发送给每一个request如果没有设置其它Request Specification。Java语言中,int类型默认值是0,相似地我们也可以设置一个默认的Request Specification。
为了设置默认的Request Specification,我们需要用RestAssured class中static属性requestSpecification,当没有设置其它RequestSpecification,默认的RequestSpecification会自动发送。如果我们有另外一个requestSpecification,默认的requestSpecification将会被新的requestSpecification覆盖。
完整代码:
import org.junit.Test;
import org.junit.BeforeClass;
import io.restassured.RestAssured;
import io.restassured.specification.RequestSpecification;
import io.restassured.response.Response;
public class DefaultRequestSpecificationExample {
@BeforeClass
public static void setupDefaultRequestSpecification()
{
// Creating request specification using given()
RequestSpecification request1= RestAssured.given();
// Setting Base URI
request1.baseUri("https://restful-booker.herokuapp.com");
// Setting Base Path
request1.basePath("/booking");
RestAssured.requestSpecification = request1;
}
@Test
public void useDefaultRequestSpecification()
{
// It will use default RequestSpecification
Response res = RestAssured.when().get();
System.out.println("Response for default: "+res.asString());
}
@Test
public void overrideDefaultRequestSpecification()
{
// Creating request specification using with()
RequestSpecification request2= RestAssured.with();
// Setting Base URI
request2.baseUri("https://restful-booker.herokuapp.com");
// Setting Base Path
request2.basePath("/ping");
// Overriding default request specification
Response res = RestAssured.given().spec(request2).get();
System.out.println("Response for overriding: "+res.asString());
}
}
输出:
Response for default: [{"bookingid":22},{"bookingid":9},{"bookingid":27},{"bookingid":3},{"bookingid":28},{"bookingid":11},{"bookingid":16},{"bookingid":21},{"bookingid":20},{"bookingid":5},{"bookingid":1},{"bookingid":33},{"bookingid":8},{"bookingid":7},{"bookingid":26},{"bookingid":17},{"bookingid":30},{"bookingid":13},{"bookingid":23},{"bookingid":19},{"bookingid":29},{"bookingid":18},{"bookingid":14},{"bookingid":6},{"bookingid":32},{"bookingid":2},{"bookingid":4},{"bookingid":12},{"bookingid":10},{"bookingid":31}]
Response for overriding: Created
Process finished with exit code 0