【问题标题】:Simulate session using WithServer使用 WithServer 模拟会话
【发布时间】:2015-12-05 08:11:46
【问题描述】:

我正在尝试将测试从使用 FakeRequest 移植到使用 WithServer。

为了模拟带有 FakeRequest 的会话,可以使用 WithSession("key", "value"),如本文中所建议的那样: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(..)(这是否有意义?),但无济于事。

有什么想法吗? 谢谢

【问题讨论】:

    标签: session playframework playframework-2.0


    【解决方案1】:

    于是发现了这个问题,比较老了:

    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 已被弃用

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-18
      • 2021-11-11
      • 2023-03-29
      相关资源
      最近更新 更多