Mongodb Scalamock:模拟泛型case类会导致类型不匹配
我在应用程序中使用Mongodb作为持久性,目前正在为代码编写测试。我的伤口如下Mongodb Scalamock:模拟泛型case类会导致类型不匹配,mongodb,scala,unit-testing,scalamock,Mongodb,Scala,Unit Testing,Scalamock,我在应用程序中使用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: MongoColle
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) => ())
}
}
val mongoCollection: MongoCollection[Document] = mock[MongoCollection[Document]]
(mongoDatabase.getCollection[Document] _).expects("order").once().returning(mongoCollection)
我的mock正在通过使用implicits正确注入。我正在模拟getCollection调用,它本身应该会导致另一个模拟,这次是类型
MongoCollection[org.mongodb.scala.bson.collection.immutable.Document]
所以我现在做的是
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) => ())
}
}
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]) {
....
}
似乎通用参数没有正确地“调整”(我不确定如何调用它)到文档中,预先指定类型参数应该起作用,或者,如果您的接口是完全抽象的,您可以使用代理模拟:
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
}
}
嗨,看起来你遇到了这个错误:。这项工作正在进行中,但很难完成fix@PhilippM有什么解决办法吗?