我想像 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)了 Application
和 WSClient
并且测试不依赖于全局状态或工厂。
为了使用这个例子,你还需要这个小的辅助函数来创建一个基于注入(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/