问题
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