【问题标题】:Mocking a Service that returns Cats EitherT with Guice and MockitoSugar使用 Guice 和 MockitoSugar 模拟返回 Cats EitherT 的服务
【发布时间】:2019-05-16 14:23:30
【问题描述】:

我正在尝试编写一些功能测试,并且我想模拟一个使用外部提供程序的服务。但我无法为返回EitherT的函数设置模拟

这是实现调用外部服务的 Trait

@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(

我只想模拟成功的响应,因为这是我正在测试的。有没有办法做到这一点?

【问题讨论】:

    标签: scala playframework mockito scala-cats mockito-scala


    【解决方案1】:

    使用 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 应用程序的所有模拟在每次测试前自动重置。

    查看here了解更多详情

    【讨论】:

    • 谢谢你的回答,mockito-scala-cats 支持间谍吗?
    • 是的,它只是存根 api 的语法糖
    【解决方案2】:

    尝试通过向rightT 提供一些类型参数来帮助编译器,就像这样

    EitherT.rightT[Future, String](Json.parse("""{"key": "value"}"""))
    

    而不是

    EitherT.rightT(Json.parse("""{"key": "value"}"""))
    

    【讨论】:

    • 谢谢@Mario_Galic 成功了,我做到了,import cats.implicits._
    • @Mario_galic 检查 mockito-scala-cats,它为该场景提供了更简单的语法
    猜你喜欢
    • 2019-04-09
    • 1970-01-01
    • 2022-01-22
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多