3

我在我的应用程序中使用 Mongodb 作为持久性,我目前正在为我的代码编写测试。我的 CUT 如下所示

implicit def storageHandler[M[_]: Monad](
    implicit mongoDatabase: MongoDatabase
) = new Storage.Handler[M] {
    override def store(order: Order): M[Unit] = Monad[M].pure {
      val collection: MongoCollection[Document] = mongoDatabase.getCollection("order")

      val document: Document = Document(order.asJson.toString)

      collection.insertOne(document).subscribe((x: Completed) => ())
   }
}

我的模拟通过使用隐式得到正确注入。我正在嘲笑 getCollection 调用,它本身应该导致另一个模拟,这次是类型

MongoCollection[org.mongodb.scala.bson.collection.immutable.Document]

所以我正在做的是以下

val mongoCollection: MongoCollection[Document] = mock[MongoCollection[Document]]

(mongoDatabase.getCollection[Document] _).expects("order").once().returning(mongoCollection)

但这会导致以下错误

type mismatch;
[error]  found   : com.mongodb.async.client.MongoCollection[TResult]
[error]  required: com.mongodb.async.client.MongoCollection[org.mongodb.scala.bson.collection.immutable.Document]
[error]  val mongoCollection: MongoCollection[Document] = mock[MongoCollection[Document]]

TResult 是来自 mongoCollection 的通用参数,如下所示:

case class MongoCollection[TResult](private val wrapped: JMongoCollection[TResult]) { 
.... 
}

似乎通用参数没有正确“调整”(我不知道如何调用它)到 Document

4

1 回答 1

1

预先指定类型参数应该可以工作,或者,如果您的接口是完全抽象的,您可以为此使用代理模拟:

import org.scalamock.scalatest.MixedMockFactory
import org.scalatest.{FlatSpec, Matchers}

import scala.reflect.ClassTag

class Issue170Test extends FlatSpec with Matchers with MixedMockFactory {
  behavior of "ScalaMock"

  it should "mock this" in {
    class Foo[T: ClassTag]
    "val m = mock[Foo[Nothing]]" should compile // this one fails :(
  }

  trait TotallyAbstract[T] {
    def foo: Int
    def bar: T
  }

  it should "work with this workaround" in {
    class Foo[T: ClassTag]
    abstract class Foo2 extends Foo[Int] // workaround: specify type parameter
    "val m = mock[Foo2]" should compile
    "val m2 = Proxy.mock[TotallyAbstract[Int]]" should compile
  }
}
于 2017-09-25T16:02:09.750 回答