0

我正在尝试使用 ScalaTest 和 ScalaMock 测试以下代码行。

val responseFuture = wsClient.url(url).withQueryString(params: _*).get()

wsClienttype is THttpClient,它是play.api.libs.ws.WS.

鉴于:

val mockHttpClient = mock[THttpClient]

被正确注入到我的测试类中,测试代码是这样的:

val expectedUrl = "some url"
val mockRequestHolder = mock[WSRequestHolder]
inSequence {
  (mockHttpClient.url _).expects(expectedUrl).returns(mockRequestHolder)
  (mockRequestHolder.withQueryString _).expects(where {
    (parameters: Seq[(String, String)]) => {
      // assertions on parameters
      // ...
      true
    }
  }).returns(mockRequestHolder)

  val stubResponse = stub[WSResponse]
  val jsonBody = "{}"
  (stubResponse.json _).when().returns(Json.parse(jsonBody))
  (mockRequestHolder.get _).expects().returns(Future(stubResponse))
}

IntelliJ 突出显示mockRequestHolder.get一个错误:无法解析符号获取。尽管如此,我还是能够运行测试,但模拟显然不起作用,并且我得到:java.util.NoSuchElementException: JsError.get。

当我尝试模拟 的任何其他方法时,模拟正在工作WSRequestHolder,但不是使用 method get

这是 ScalaMock 错误还是我做错了什么?

4

2 回答 2

1

我不知道你是否已经解决了这个问题,但我最近尝试做类似的事情,我有点让它使用以下代码:

val wsClientMock = mock[WSClient]
val wsRequestMock = mock[WSRequest]
val wsResponseMock = mock[WSResponse]
(wsRequestMock.withAuth _).expects(username, password, WSAuthScheme.BASIC).returning(wsRequestMock)
(wsRequestMock.get _).expects().returning(Future[WSResponse](wsResponseMock))
(wsClientMock.url _).expects(bootstrapUrl).returning(wsRequestMock)
(wsResponseMock.status _).expects().returning(200)

“有点”,因为我还需要模拟响应,否则我会得到类似的结果

ERROR[default-akka.actor.default-dispatcher-4] OneForOneStrategy - Unexpected call: json()

由于调用 WSClient 的代码正在调用 WSResponse 的方法 .json。

于 2015-12-15T13:04:01.397 回答
0

抱歉,我不知道 Scala Mock,但我建议你看看 MockWS 一个带有模拟 WS 客户端的库:play-mockws

使用 MockWS,您可以定义一个返回 Route 的 Action 的部分函数。这使您能够精确地配置模拟答案并测试您的 http 客户端代码。

于 2015-08-21T21:24:17.107 回答