使用RestAssured维护会话

5
如何在restassured中设置会话属性?在我的应用程序代码中,我们有类似以下的内容:
String userId = request.getSession().getAttribute(“userid”);
如何在这里将userId设置为会话属性(在restassured测试用例中)?
如何为所有请求(多个连续请求)维护同一个会话?
当我发送多个请求时,它认为每个请求都是新的,并且会话从服务器端失效,我想在后续调用之间维护会话。
我尝试在cookie中设置jsessionid并在第二个请求中发送它,但是当我在服务器端进行调试时,它没有加载已创建的会话,而是创建了不同的会话。因此,在我第一次发送请求时设置的属性不显示。
使用直接HttpClient进行相同操作时,它可以工作,但是使用RestAssured时无法正常工作。
使用HttpClient工作的代码如下:
HttpClient httpClient = util.getHttpClient(); 

//第一次请求

HttpResponse response=httpClient.execute(postRequest); 

我从响应中提取了jessionid,并将其设置在第二个请求中。

HttpGet getRequest = new HttpGet(Client.endPointUrl);
 getRequest.addHeader("content-type", "application/json");
 getRequest.addHeader("accept", "application/json");
 getRequest.addHeader("Origin", Client.endPointUrl);
 getRequest.addHeader("Referer", Client.endPointUrl);
 getRequest.addHeader("Auth-Token", authToken);
 getRequest.addHeader("Set-Cookie", jsessionId);

//在从响应中提取的jessionid设置后进行第二次请求
HttpResponse eventsResponse = httpClient.execute(getRequest); 

上面的代码完全正常运行,我得到了期望的响应。一个观察是我使用同一个httpClient对象调用两个请求。

然而,如果我尝试使用 RestAssured 来做相同的事情,它就不起作用。

RestAssured.baseURI = "http://localhost:8080";
 Response response=RestAssured.given().header("Content-Type","application/json").
                     header("Origin","http://localhost:8080").
                     header("Referer","http://localhost:8080").
                     body("{"+  
                           "\"LoginFormUserInput\":{"+  
                            "\"username\":\"test\","+
                             "\"password\":\"password\""+
                          "}"+
                    "}")
                     .when().post("/sample/services/rest/validateLogin").then().extract().response();

 JsonPath js=Util.rawToJson(response);
 String sessionId=js.get("sessionID");
 System.out.println(sessionId);

 for (Header header:response.getHeaders()) {
     if ("Set-Cookie".equals(header.getName())) {
         id= header.getValue().split(";")[0].trim();
        String[] arr=jsessionId.split("=");
        jsessionId=arr[0];
     break;
     } 
 }


 response=RestAssured.given().header("Auth-Token",sessionId).header("Content-Type","application/json").
    cookie("JSESSIONID",jsessionId).
    header("Origin","http://localhost:8080").
    header("Referer","http://localhost:8080").
     body("{}").
     when().
     post("/sample/services/rest/getAllBooks").then().contentType("").extract().response();

我尝试使用以下方法为所有请求重复使用相同的httpclient,但它并没有起作用。
RestAssured.config = RestAssured.config().httpClient( new HttpClientConfig().reuseHttpClientInstance());

有人能回答这个问题吗?我也遇到了同样的问题。 - Praveen Pandey
1个回答

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接