6中对服务器进行单元测试

6中对服务器进行单元测试

本文介绍了现在不赞成使用Action singleton,如何在Play 2.6中对服务器进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在撰写本文时,播放2.6 处于发行候选状态.Action单例已被弃用,因此,此处有关测试的所有信息均已弃用:

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

即使用DSL进行模拟服务器路由,如下所示:

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 => ...

引起弃用警告.

是否有办法避免这种情况,还是我们只需要等待他们更新其测试DSL?

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

推荐答案

是的,在Play框架2.6中有一种使用ScalaTest进行此操作的新方法.您需要使用Guice来构建Application并注入您自己的RouterProvider.考虑以下示例:

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")))
    }
  }
}

这篇关于现在不赞成使用Action singleton,如何在Play 2.6中对服务器进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 10:24