Testing a Play2 application with SecureSocial using dependency injection

后端 未结 1 2119
陌清茗
陌清茗 2020-12-17 06:11

Thanks a lot for any guidance!

The SecureSocial plugin works fine when I run it from the browser, but I would like to be able to test the rest of my Play app now.

相关标签:
1条回答
  • 2020-12-17 06:47

    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.
        }
    
    0 讨论(0)
提交回复
热议问题