模拟返回 fs2.Stream 的方法 [英] Mocking a method which returns an fs2.Stream

查看:60
本文介绍了模拟返回 fs2.Stream 的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能用 Mockito 模拟来模拟返回 fs2.Stream 的方法?

Why isn't it possible to mock a method that returns an fs2.Stream with a Mockito mock?

Mockito 抱怨我试图返回 FreeC 而不是 Stream.为什么会这样,我怎样才能让它工作?

Mockito is complaining that I am trying to return a FreeC instead of a Stream. Why is that and how can I get it working?

以下代码:

import cats.effect.IO
import fs2.Stream
import org.mockito.Mockito.when
import org.scalatest.FlatSpec
import org.scalatest.mockito.MockitoSugar

trait MyTrait {
  def method: Stream[IO, Int]
}

class TestSpec extends FlatSpec with MockitoSugar {

  val m: MyTrait = mock[MyTrait]
  val emptyReturn: Stream[IO, Int] = Stream.emits(List.empty[Int])

  when(m.method).thenReturn(emptyReturn)

  ...
}

给出这个错误:

TestSpec:
TestSpec *** ABORTED ***
  org.mockito.exceptions.misusing.WrongTypeOfReturnValue: Stream cannot be returned by method()
method() should return FreeC
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
   Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
   - with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.
  at TestSpec.<init>(TestSpec.scala:15)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
  at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
  at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
  at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
  at java.lang.Class.newInstance(Class.java:442)
  at org.scalatest.tools.Framework$ScalaTestTask.execute(Framework.scala:435)
  at sbt.TestRunner.runTest$1(TestFramework.scala:76)
  at sbt.TestRunner.run(TestFramework.scala:85)
  at sbt.TestFramework$$anon$2$$anonfun$$init$$1$$anonfun$apply$8.apply(TestFramework.scala:202)
  ...

推荐答案

mockito 对模拟 (MyTrait) 的运行时检查和 fs2.Stream 是 FreeC 的值类,这似乎有些奇怪.

Seems to be something weird going on with mockito's runtime inspection of the mock (MyTrait) and fs2.Stream being a value class of FreeC.

一种解决方案(除了不模拟)是在测试实现中强制 fs2.Stream 在运行时装箱.我通过将 MyTrait 转换为 MyTrait[F[_]] 并将 def 方法:Stream[IO, Int] 转换为 def 方法:F[Int]

One solution (other than just not mocking) would be to force fs2.Stream to be boxed at runtime in your test implementation. I managed this by converting MyTrait into MyTrait[F[_]] and def method: Stream[IO, Int] into def method: F[Int]

然后你模拟 MyTrait[Stream[IO, ?]].

Then you mock MyTrait[Stream[IO, ?]].

希望对你有所帮助

此问题已从 mockito-scala v1.0.3 开始修复

这篇关于模拟返回 fs2.Stream 的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆