1

我想测试WS客户端与服务器的假像它的播放2.4文档在这里解释真实:https://www.playframework.com/documentation/2.4.x/ScalaTestingWebServiceClients播放2.4 Scaldi WS测试

但我做DI与Scaldi,我不能够适应Play的文档代码使用Scaldi。

有人可以帮助我吗?

适应的代码大多是这种(来自播放DOC):

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

回答

3

进行集成测试的一般方法的一个例子可以在这里找到:

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,就像在你的榜样。区别在于ApplicationWSClient被注入并且测试不依赖于全局状态或工厂。

为了使用这个例子中,你还需要它创建基于注入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() 
    } 
} 

播放已经提供了一些辅助功能外的开箱创建一个测试服务器,但其中大部分要么重新初始化依赖Guice的应用程序。那是因为你需要创建自己的简化版本。这个功能可能是包含在scaldi-play中的一个好选择。

+0

确定它的工作原理,但如果我不喜欢使用构造函数参数来做我的注入和只注入一些属性。 例如: **类GitHubClient(隐式INJ:进样器)延伸注射{ VAL WS =注入[WSClient] VAL的baseUrl =注入[字符串]( “的baseUrl”) ... } ** –

+0

确定,这不应该是一个问题。您只需将它绑定到某个应用程序模块中,然后将其注入到测试中即可。 – tenshi

2

朱尔斯,

迟到的回应,但我只是经历了这个自己。以下是我如何使用wsUrl测试ScalaTest(Play Spec),测试服务器和WSTestClient。这是玩2.5.4。该项目在这里:reactive-rest-mongo

class UsersSpec extends PlaySpec with Injectable with OneServerPerSuite { 

    implicit override lazy val app = new ScaldiApplicationBuilder() 
    .build() 

    "User APIs" must { 

    "not find a user that has not been created" in { 
     val response = Await.result(wsUrl("https://stackoverflow.com/users/1").get, Duration.Inf) 
     response.status mustBe NOT_FOUND 
     response.header(CONTENT_TYPE) mustBe None 
     response.bodyAsBytes.length mustBe 0 
    } 
    } 
}