Scala 模仿使用Guice和MockitoSugar返回Cats EitherT的服务
我正在尝试编写一些功能测试,我想模拟一个使用外部提供者的服务。但是我不能为返回Scala 模仿使用Guice和MockitoSugar返回Cats EitherT的服务,scala,playframework,mockito,scala-cats,mockito-scala,Scala,Playframework,Mockito,Scala Cats,Mockito Scala,我正在尝试编写一些功能测试,我想模拟一个使用外部提供者的服务。但是我不能为返回EitherT 这是其实现调用外部服务的特性 @ImplementedBy(classOf[ExternalServiceImpl]) trait ExternalService { def index: EitherT[Future, String, JsValue] } 在我设置的CustomAppPerSuite特性中 val mockExternalService = mock[ExternalServi
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(
我只想模拟成功的响应,因为这是我正在测试的。有什么方法可以做到这一点吗?尝试通过向
right
提供一些类型参数来帮助编译器,就像这样
EitherT.rightT[Future, String](Json.parse("""{"key": "value"}"""))
而不是
EitherT.rightT(Json.parse("""{"key": "value"}"""))
对于mockito scala猫,你可以用一种更简洁的方式来写
Json.parse("""{"key": "value"}""") willBe returnedF by externalService.index
//or
externalService.index shouldReturnF Json.parse("""{"key": "value"}""")
图书馆将查看externalService.index
的返回类型,并获得相应的cats.Applicative
,以使此工作顺利进行
如果您在ScalateTest上运行,另一个优点是您可以混合使用ResetMocksAfterEachTest
,并在每次测试之前自动重置连接到play fake应用程序中的所有模拟
查看更多详细信息谢谢@Mario_Galic它成功了,我做到了,并且导入了猫。隐式。@Mario_Galic Check mockito scala cats,它为该场景提供了一个更简单的语法谢谢你的回答,mockito scala cats支持spy吗?是的,它只是Stubing api的语法糖