如何配置Java保证库不重用cookie

时间:2019-02-01 18:48:27

标签: java cookies session-cookies rest-assured

正在尝试重用testng api测试中的可放心的get调用,但是可放心的实例使用的是从先前响应中收到的cookie。 尝试过RestAssured.reset();但这无助于刷新我们从先前的请求/响应中获得的cookie。

此问题的原因-如果请求上存在会话cookie,则get端点的行为会有所不同。

@Test // TestNG test
public void test_1(){

    //Set Cookie
    Cookie cookie = new Cookie.Builder("COOKIENAME","COOKIEVALUE").setDomain("*.com").setPath("/").setExpiryDate(SOMELATERDATE).build();

    RestAssured.baseURI = https://ENV_URL;
    Response response = RestAssured.given().log().all()
        .cookies(new Cookies(cookie)).when().get("/END_POINT").then().extract().response().prettyPeek();

    RestAssured.reset();
}

@Test // TestNG test
public void test_2(){

    //Set Cookie
    Cookie cookie = new Cookie.Builder("COOKIENAME", "COOKIEVALUE").setDomain("*.com").setPath("/").setExpiryDate(SOMELATERDATE).build();

    RestAssured.baseURI = https://ENV_URL;
    // Still Reuses the cookie received from previous response
    Response response = RestAssured.given().log().all()
        .cookies(new Cookies(cookie)).when().get("/END_POINT").then().extract().response().prettyPeek();

    RestAssured.reset();
}

1 个答案:

答案 0 :(得分:0)

使用CookieFilter。如果要排除特定的Cookie,则可以使用以下代码。

    @Test 
    public void sampletest(){

        CookieFilter cookieFilter = new CookieFilter(); 
        Response response = RestAssured.given().
         cookie("foo", "bar").
         filter(cookieFilter). // Reuse the same cookie filter
                      // if "foo" is stored in cookieFilter it won't be applied because it's already applied explicitly
 expect().
         statusCode(200).
 when().
         get("/y");

    }