模拟返回fs2.Stream的方法

时间:2018-03-02 14:13:13

标签: scala mockito fs2

为什么不能模拟一个返回带有Mockito模拟的fs2.Stream的方法?

Mockito抱怨​​说我正在尝试返回FreeC而不是Stream。为什么这样,我怎样才能让它发挥作用?

以下代码:

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)
  ...

2 个答案:

答案 0 :(得分:3)

我不确定在模仿方面,但是根本不需要使用模仿;

val m: MyTrait = new MyTrait {
  def method: Stream[IO, Int] = Stream.emits(List.empty[Int]).covary[IO]
}

答案 1 :(得分:2)

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

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

然后您嘲笑MyTrait [Stream [IO,?]]。

希望这会有所帮助


此问题已在mockito-scala v1.0.3版本中得到修复