使用 WithServer 模拟会话
Simulate session using WithServer
我正在尝试将测试从使用 FakeRequest 移植到使用 WithServer。
为了模拟与 FakeRequest 的会话,可以使用 WithSession("key", "value")
post 中的建议:Testing controller with fake session
然而,当使用 WithServer 时,测试现在看起来像:
"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")
}
由于没有可用的 WithSession(..)
方法,我尝试了 WithHeaders(..)
(这是否有意义?),但无济于事。
有什么想法吗?
谢谢
所以我找到了这个问题,比较老:
Add values to Session during testing (FakeRequest, FakeApplication)
该问题的第一个答案似乎是将 .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 已弃用
我正在尝试将测试从使用 FakeRequest 移植到使用 WithServer。
为了模拟与 FakeRequest 的会话,可以使用 WithSession("key", "value")
post 中的建议:Testing controller with fake session
然而,当使用 WithServer 时,测试现在看起来像:
"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")
}
由于没有可用的 WithSession(..)
方法,我尝试了 WithHeaders(..)
(这是否有意义?),但无济于事。
有什么想法吗? 谢谢
所以我找到了这个问题,比较老:
Add values to Session during testing (FakeRequest, FakeApplication)
该问题的第一个答案似乎是将 .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 已弃用