gpt4 book ai didi

mongodb - Scalamock:模拟通用案例类会导致类型不匹配

转载 作者:可可西里 更新时间:2023-11-01 09:54:04 25 4
gpt4 key购买 nike

我在我的应用程序中使用 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) => ())
}
}

我的 mock 正在使用隐式正确注入(inject)。我正在模拟 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]) { 
....
}

似乎通用参数没有正确地“调整”(我不确定如何调用它)到文档

最佳答案

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

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

关于mongodb - Scalamock:模拟通用案例类会导致类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46338256/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com