模拟一个没有参数但带有隐式参数的方法

dou*_*laz 3 unit-testing scala scalatest scalamock

abstract trait MyApi {

  def getResult()(implicit ec: ExecutionContext): Future[String]

}
Run Code Online (Sandbox Code Playgroud)

以下不起作用:

val m = mock[MyApi]
(m.getResult _).expects() returning "..."
Run Code Online (Sandbox Code Playgroud)

它失败了:

java.lang.ClassCastException: org.scalamock.MockFunction1 cannot be cast to org.scalamock.MockFunction0
Run Code Online (Sandbox Code Playgroud)

注意:http ://scalamock.org/user-guide/advanced_topics/中给出的示例仅在方法至少有一个参数时才有用.所以我们不能像使用scalamock在scala中使用ClassTag的模拟方法那样使用解决方案

Ed *_*aub 7

我想你没有看正确的例子.查看示例4的隐式参数:

class Codec()

trait Memcached {
  def get(key: String)(implicit codec: Codec): Option[Int]
}

val memcachedMock = mock[Memcached]

implicit val codec = new Codec
(memcachedMock.get(_ : String)(_ : Codec)).expects("some_key", *).returning(Some(123))
Run Code Online (Sandbox Code Playgroud)

在你的情况下,当然,非隐式params为null,所以你想要:

(m.getResult()(_: ExecutionContext)).expects(*) returning "..."
Run Code Online (Sandbox Code Playgroud)