gpt4 book ai didi

scala - 使用 Scalamock 模拟 Play WSRequestHolder get 方法

转载 作者:行者123 更新时间:2023-11-28 21:28:38 24 4
gpt4 key购买 nike

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

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

wsClient类型为THttpClient,是play.api.libs.ws.WS的封装

鉴于:

val mockHttpClient = mock[THttpClient]

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

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 的任何其他方法时,模拟正在工作,但不是使用方法 get

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

最佳答案

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

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方法。

关于scala - 使用 Scalamock 模拟 Play WSRequestHolder get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31807112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com