Scala:Mock init 因 Cats IO 类型参数而失败

Scala: Mock init fails with Cats IO type parameter

在编写测试时我遇到了以下异常:

java.lang.ClassCastException: codegen.java.lang.Object$MockitoMock1592186 cannot be cast to cats.effect.IO (MyRepositorySpec.scala:19)

当 运行 此测试代码与 specs2:

时发生
class MyRepositorySpec extends Specification with Mockito with TestData {
    ...
    val m = mock[MyDAO[IO]].smart
    m.createTable returns IO { Right[Throwable, Int](1) } // <- this is line 19

    val r = new MyRepository[IO](m)
    r.setup.unsafeRunSync() must beNone
    ...
}

MyDAO 看起来像这样:

class MyDAO[M[_] : Monad](val transactor: Transactor[M])(implicit val AE: ApplicativeError[M, Throwable]) extends DataAccessObject[M, MyObject]

DataAccessObject 这样的:

trait DataAccessObject[M[_], T <: Entity]

我不知道如何 fix/correctly 实现它。任何帮助,将不胜感激。谢谢!

尝试

class IOMyDAO(override val transactor: Transactor[IO]) extends MyDAO[IO](transactor)

val m = mock[IOMyDAO].smart

基于此answer


您应该尝试使用 org.mockito.Mockito#when 而不是 specs2 的内部方法匹配功能:

when(m.createTable) thenReturn IO { Right[Throwable, Int](1) }

而不是

m.createTable returns IO { Right[Throwable, Int](1) }