Scala:Mock init使用Cats IO类型参数失败

时间:2017-09-27 12:54:57

标签: scala unit-testing mockito specs2 scala-cats

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

java.lang.ClassCastException: codegen.java.lang.Object$MockitoMock$641592186 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]

我不知道如何修复/正确实现这一点。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

尝试

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