Session 使用WithServer模拟会话
我正在尝试将测试从使用FakereRequest移植到使用WithServer 为了使用FakereRequest模拟会话,可以使用Session 使用WithServer模拟会话,session,playframework,playframework-2.0,Session,Playframework,Playframework 2.0,我正在尝试将测试从使用FakereRequest移植到使用WithServer 为了使用FakereRequest模拟会话,可以使用和session(“key”,“value”),如本文所述: 但是,在与服务器一起使用时,测试现在看起来如下所示: "render the users page" in WithServer { val users = await(WS.url("http://localhost:" + port + "/users").get) users.status
和session(“key”,“value”)
,如本文所述:
但是,在与服务器一起使用时,测试现在看起来如下所示:
"render the users page" in WithServer {
val users = await(WS.url("http://localhost:" + port + "/users").get)
users.status must equalTo(OK)
users.body must contain("Users")
}
由于没有可用的with session(…)
方法,因此我尝试了with headers(…)
(这有意义吗?),但没有效果
有什么想法吗?
谢谢所以我发现了这个问题,这个问题比较老: 这个问题的第一个答案似乎是一个pull请求,将
.WithSession(…)
添加到FakeRequest,但它不适用于WS.url
第二个答案似乎给了我所需要的:
创建cookie:
val sessionCookie = Session.encodeAsCookie(Session(Map("key" -> "value")))
创建并执行请求:
val users = await(WS.url("http://localhost:" + port + "/users")
.withHeaders(play.api.http.HeaderNames.COOKIE -> Cookies.encodeCookieHeader(Seq(sessionCookie))).get())
users.status must equalTo(OK)
users.body must contain("Users")
最后,断言将正确传递,而不是将我重定向到登录页面
注意:我使用的是Play 2.4,所以我使用Cookies.encodeCookieHeader,因为Cookies.encode已被弃用