1

我希望能够使用 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()并返回结果。

4

1 回答 1

1

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

(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall { test =>
    Right(test.productElement(2).asInstanceOf[() => T]())
}
于 2018-05-17T06:44:26.640 回答