REST Assured 17 - 设置默认的RequestSpecification

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值