scala - 使用 Guice 和 MockitoSugar 模拟返回 Cats EitherT 的服务
问题描述
我正在尝试编写一些功能测试,并且我想模拟一个使用外部提供程序的服务。但我无法为返回的函数设置模拟EitherT
这是其实现调用外部服务的特征
@ImplementedBy(classOf[ExternalServiceImpl])
trait ExternalService {
def index: EitherT[Future, String, JsValue]
}
在我设置的 CustomAppPerSuite 特征中
val mockExternalService = mock[ExternalService]
implicit override lazy val app = new GuiceApplicationBuilder()
.in(Mode.Test)
.overrides(bind[ExternalService].toInstance(mockExternalService))
.build()
val externalService = app.injector.instanceOf[ExternalService]
然后当我尝试模拟成功的响应时
"ExternalController#index" should {
"return index data" in {
doReturn(EitherT.rightT(Json.parse("""{"key": "value"}""")).when(externalService).index
val fakeRequest = FakeRequest(GET, "/api/external")
val result = externalController.index().apply(fakeRequest)
status(result) mustBe OK
}
但我得到这个错误
[error] found : cats.data.EitherT[cats.package.Id,Nothing,JsValue]
[error] required: cats.data.EitherT[scala.concurrent.Future,String,JsValue]
[error] def index = EitherT.rightT(
我只想嘲笑成功的响应,因为这是我正在测试的。有没有办法做到这一点?
解决方案
使用 mockito-scala-cats 你可以用更简洁的方式来写
Json.parse("""{"key": "value"}""") willBe returnedF by externalService.index
//or
externalService.index shouldReturnF Json.parse("""{"key": "value"}""")
库将查看的返回类型externalService.index
并获取适当cats.Applicative
的 (s) 以使这项工作顺利进行。
如果您在 Scalatest 上运行,另一个优势是您可以混合ResetMocksAfterEachTest
并让您连接到 play fake 应用程序的所有模拟在每次测试之前自动重置。
在这里查看更多详情
推荐阅读
- javascript - 对象内的对象数组未定义
- reactjs - 有条件地为 TouchableHighlight 渲染 onPress
- python - 取 nlargest 5 并对 pandas 中的其余部分求和/计数
- ruby-on-rails - 用户属于组织,只能查看/编辑其公司 Ruby on Rails 添加的项目
- angular - p-confirmDialog 没有得到关注
- python - Heroku 没有检测到静态文件的 Django 设置
- hadoop - 将 RDBMS 中保存的非结构化数据卸载到 Hadoop
- linux - 如何使用“ln”为 linux 上的目录创建链接?
- html - 我可以自定义编辑 WordPress 图像页面吗?
- javascript - 在谷歌图表中自定义haxis标签