如何使用 ScalaMock 按名称函数模拟调用?

How to mock a call by name function using ScalaMock?

我希望能够使用 ScalaMock 模拟我的按名称调用函数,因此它可以 运行 我的模拟中传递的函数。

class MyTest extends Specification with MockFactory {

  trait myTrait {
    def myFunction[T](id: Int, name: String)(f: => T): Either[ErrorCode,T]
  }

  def futureFunction() = Future {
    sleep(Random.nextInt(500))
    10
  }

  "Mock my trait" should {
    "work" in {
      val test = mock[myTrait]

      (test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
        _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
      }
      test.myFunction(25)("test")(futureFunction()) must beEqualTo(10)
    }
  }

}

我试过这样模拟函数:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall {
    _.productElement(2).asInstanceOf[() => Either[ErrorCode,T]]()
  }

但是当我 运行 测试时,我得到这个错误:

scala.concurrent.impl.Promise$DefaultPromise@69b28a51 cannot be cast to  Either

我如何模拟它,所以它 运行 是我的 futureFunction() 内部模拟和 return 结果。

一位朋友帮我找到了解决办法。问题与我对 myFunction() 的模拟有关。在评估之后,我将一个按名称调用的函数传递给 myFunction()(f: => T) which returns T它,myFunction() returns Either[ErrorCode, T]。所以模拟应该是这样的:

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall { test =>
    Right(test.productElement(2).asInstanceOf[() => T]())
}