我正在使用mongodb作为持久性,目前我正在为我的代码编写测试。我的剪切外观如下
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是猫卷的通用参数,看起来像这样:
case class MongoCollection[TResult](private val wrapped: JMongoCollection[TResult]) {
....
}
看来,通用参数未正确"调整"(我不确定如何称呼它)来文档
指定类型参数的预期应起作用,或者,如果您的界面完全抽象,则可以对此使用代理模拟:
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
}
}