scala - Play 2.4 Scaldi WS 测试

标签 scala testing dependency-injection playframework-2.0 scaldi

我想像 Play 2.4 文档中所解释的那样,用假服务器测试 WS 客户端:https://www.playframework.com/documentation/2.4.x/ScalaTestingWebServiceClients

但我正在使用 Scaldi 进行 DI,我无法调整 Play 的文档代码以使用 Scaldi。

有人可以帮助我吗?

适应的代码主要是这样的(来自 Play 文档):

"GitHubClient" should {
  "get all repositories" in {

    Server.withRouter() {
      case GET(p"/repositories") => Action {
        Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
      }
    } { implicit port =>
      WsTestClient.withClient { client =>
        val result = Await.result(
          new GitHubClient(client, "").repositories(), 10.seconds)
        result must_== Seq("octocat/Hello-World")
      }
    }
  }
}

最佳答案

可在此处找到集成测试的一般方法示例:

https://github.com/scaldi/scaldi-play-example/blob/master/test/IntegrationSpec.scala#L22

虽然它不是直接等效的,因为它使用 HttpUnit 而不是 WSClient。更精确的等价物是这样的:

import scaldi.play.ScaldiApplicationBuilder._
import scaldi.Injectable._

val fakeRotes = FakeRouterModule {
  case ("GET", "/repositories") => Action {
    Results.Ok(Json.arr(Json.obj("full_name" -> "octocat/Hello-World")))
  }
}

withScaldiInj(modules = fakeRotes :: Nil) { implicit inj ⇒
  val client = inject [WSClient]

  withTestServer(inject [Application]) { port ⇒
    val result = Await.result(
      new GitHubClient(client, s"http://localhost:$port").repositories(), 10.seconds)

    result must_== Seq("octocat/Hello-World")
  }
}

它使用 WSClient,就像您的示例中一样。不同之处在于注入(inject)了 ApplicationWSClient 并且测试不依赖于全局状态或工厂。

为了使用这个例子,你还需要这个小的辅助函数来创建一个基于注入(inject)的Application的测试服务器:

def withTestServer[T](application: Application, config: ServerConfig = ServerConfig(port = Some(0), mode = Mode.Test))(block: Port => T)(implicit provider: ServerProvider): T = {
  val server = provider.createServer(config, application)

  try {
    block(new Port((server.httpPort orElse server.httpsPort).get))
  } finally {
    server.stop()
  }
}

Play 已经提供了一些开箱即用的帮助函数来创建测试服务器,但它们中的大多数要么重新初始化依赖 Guice 的应用程序。那是因为您需要创建自己的简化版本。这个函数可能是包含在 scaldi-play 中的一个很好的候选者。

关于scala - Play 2.4 Scaldi WS 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34792807/

相关文章:

Angular 7 库 - 检测到循环依赖(指令、服务、模块)

c# - Azure Blob 和表存储以更简单的方式重写代码

Scala 使用 if 匹配具有多个分支的情况

testing - Spock 和 Spock 报告 : how "catch" and customize the error message for AssertionError?

java - (合作)列表的差异与 Scala 中的堆栈不同?

Android Studio 测试显示测试结果 0/0。如何开始测试?

ruby-on-rails - Rails2.3.8 : How do I run a test using the dev environment? ruby

mvvm - Autofac MVVM-终身

scala - 如何找到两个数组列之间的共同元素?

scala - 如何以 Scala 方式执行此操作 : get the first element from Option[Seq[String]]