如何在Scala Play框架中模拟外部WS API调用 [英] how to mock external WS API calls in Scala Play framework
问题描述
我有一个现有的Scala play应用程序,该应用程序具有一个REST API,该API调用了另一个外部REST API.我想模拟外部Web服务,以返回用于内部测试的伪JSON数据.基于以下示例: https://www.playframework.com/documentation/2.6.x /ScalaTestingWebServiceClients
I have an existing Scala play application which has a REST API that calls another external REST API. I want to mock the external Web service returning fake JSON data for internal tests. Based on example from: https://www.playframework.com/documentation/2.6.x/ScalaTestingWebServiceClients
我完全按照文档"中的示例进行操作,由于不推荐使用的Action类,我遇到了编译器错误.
I followed example exactly as in Documentation and I'm getting compiler errors due to deprecated class Action.
import play.core.server.Server
import play.api.routing.sird._
import play.api.mvc._
import play.api.libs.json._
import play.api.test._
import scala.concurrent.Await
import scala.concurrent.duration._
import org.specs2.mutable.Specification
import product.services.market.common.GitHubClient
class GitHubClientSpec extends Specification {
import scala.concurrent.ExecutionContext.Implicits.global
"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")
}
}
}
}
}
object不推荐使用mvc软件包中的Action:注入ActionBuilder (例如DefaultActionBuilder)或扩展 BaseController/AbstractController/InjectedController
object Action in package mvc is deprecated: Inject an ActionBuilder (e.g. DefaultActionBuilder) or extend BaseController/AbstractController/InjectedController
这是最新官方文档中的主要示例,实际上却包含一个编译时错误,鉴于此示例不起作用,应该如何使用Scala Play轻松模拟外部API的正确方法?
And this is the primary example from latest official docs which in fact contains a compile time error, given this example doesn't work how should be the proper way to easily mock an external API using Scala Play?
推荐答案
您可以将示例更改为:
Server.withRouterFromComponents() { cs => {
case GET(p"/repositories") => cs.defaultActionBuilder {
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 should be(Seq("octocat/Hello-World"))
}
}
说实话,我不确定100%是否是最好的方法.但是,我已经向播放框架提交了 PR ,因此您可能会留意该空间以进行评论来自制造商.
To be honest, I'm not 100% sure if this is the nicest way. However I have submitted a PR to the play framework so you might watch that space for comments from the makers.
这篇关于如何在Scala Play框架中模拟外部WS API调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!