Testing a Play2 application with SecureSocial using dependency injection

一世执手 提交于 2019-11-29 05:14:26

Here's how I solved this problem. I am simulating a login (kind of) by directly adding to the Authenticator that's in memory. That returns a cookie which I include in the fake request. I'm doing this with an implicit conversion for some syntactic sugar. You can easily extend it for your particular case. My application only uses the user/pass provider, but you should be able to extend to use the other plugins.

 object TestUtils {

  @inline implicit def loggedInFakeRequestWrapper[T](x: FakeRequest[T]) = new LoggedInFakeRequest(x)

  final class LoggedInFakeRequest[T](val self: FakeRequest[T]) extends AnyVal {
    def withLoggedInUser(id: Long) = {
      val userToLogInAs:Identity = ??? //get this from your database using whatever you have in Global
      val cookie = Authenticator.create(userToLogInAs) match {
        case Right(authenticator) => authenticator.toCookie
      }
      self.withCookies(cookie)
    }
  }        
}

And the spec:

"render the index page" in {
      val home = route(FakeRequest(GET, "/").withLoggedInUser(1L)).get

      status(home) must equalTo(OK)
      //etc.
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!