如何使用ScalaMock模拟按名称调用函数?
我希望能够使用ScalaMock模拟我的按名称调用函数,这样它就可以在模拟中运行传递的函数如何使用ScalaMock模拟按名称调用函数?,scala,unit-testing,scalamock,Scala,Unit Testing,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(Rand
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(),并返回结果。一位朋友帮助我找到了解决方案。该问题与我对myFunction()的模拟有关。我将一个名函数调用传递给myFunction()(f:=>T),该函数返回T,对其求值后,myFunction()返回或[ErrorCode,T]。所以模拟应该是这样的:
(test.myFunction (_: Int)(_: String)(_: T)).expects(25, "test",*).onCall { test =>
Right(test.productElement(2).asInstanceOf[() => T]())
}
您可以尝试使用
返回(或者[ErrorCode,T])()
而不是onCall
。嗯,我需要运行它来解决它。