具有隐式泛型类型的 Scala 模拟函数

Gri*_*dou 2 scala scalamock

我正在尝试ScalaGettableData使用 scalamock 模拟 Cassandra 对象。我需要模拟以下方法:

def getMap[K : TypeConverter, V : TypeConverter](name: String) = get[Map[K, V]](name)
Run Code Online (Sandbox Code Playgroud)

TypeConverter是 aTrait并且具有隐式实现,例如:

implicit object StringConverter extends TypeConverter[String]

在我的代码中我正在调用

scalaGettableData.getMap[String, String]("myMap")

我猜它隐式转换为

scalaGettableData.getMap[StringConverter, StringConverter]("myMap")

我的测试代码如下:

val cassandraRow1 = mock[ScalaGettableData]
(cassandraRow1.getMap[String, String] _).expects("localizations_config").returning(Map("key1" -> "value1"))`
Run Code Online (Sandbox Code Playgroud)

但我收到编译错误:

Error:(28, 26) _ must follow method; cannot follow (name: String)(implicit evidence$3: com.datastax.spark.connector.types.TypeConverter[String], implicit evidence$4: com.datastax.spark.connector.types.TypeConverter[String])Map[String,String] <and> (index: Int)(implicit evidence$3: com.datastax.spark.connector.types.TypeConverter[String], implicit evidence$4: com.datastax.spark.connector.types.TypeConverter[String])Map[String,String]
Run Code Online (Sandbox Code Playgroud)

我应该如何嘲笑这个方法?

Phi*_*ipp 5

也许这个例子有帮助:

"implicit parameters" should "be mockable" in {
  trait Bar[T]
  trait Foo {
    def getMap[K : Bar](name: String): Int
  }

  val m = mock[Foo]
  (m.getMap[Long](_: String)(_: Bar[Long])) expects(*, *) returning 42 once()

  implicit val b = new Bar[Long] {}
  m.getMap("bar")
}
Run Code Online (Sandbox Code Playgroud)

实际上,Scala 编译器将类型参数K : Bar转换为第二个参数列表,在此示例中使用 显式模拟了该列表(_: Bar[Long])