How to unit test servers in Play 2.6 now that Action singleton is deprecated

送分小仙女□ 提交于 2020-01-05 08:23:09

问题


At the time of writing, Play 2.6 is in release candidate state. The Action singleton has been deprecated, thus, all the information about testing here is deprecated:

https://www.playframework.com/documentation/2.6.0-RC2/ScalaTestingWebServiceClients

i.e. using the DSL for mock server routing like so:

Server.withRouter() {
  case GET(p"/repositories") => Action {
    Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
  }
} { implicit port => ...

Causes deprecation warnings.

Is there a way to circumvent this or do we just need to wait for them to update their testing DSL?


回答1:


Yes, there is a new way to do this with ScalaTest in Play framework 2.6. You need to use Guice to build an Application and inject your own RouterProvider. Consider this example:

class MyServiceSpec
  extends PlaySpec
    with GuiceOneServerPerTest {

  private implicit val httpPort = new play.api.http.Port(port)

  override def newAppForTest(testData: TestData): Application =
    GuiceApplicationBuilder()
      .in(Mode.Test)
      .overrides(bind[Router].toProvider[RouterProvider])
      .build()

  def withWsClient[T](block: WSClient => T): T =
    WsTestClient.withClient { client =>
      block(client)
    }

  "MyService" must {

    "do stuff with an external service" in {
      withWsClient { client =>
        // Create an instance of your client class and pass the WS client
        val result = Await.result(client.getRepositories, 10.seconds)
        result mustEqual List("octocat/Hello-World")
      }
    }
  }
}

class RouterProvider @Inject()(action: DefaultActionBuilder) extends Provider[Router] {
  override def get: Router = Router.from {
    case GET(p"/repositories") => action {
      Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
    }
  }
}


来源:https://stackoverflow.com/questions/44516955/how-to-unit-test-servers-in-play-2-6-now-that-action-singleton-is-deprecated

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