【发布时间】:2018-05-17 14:44:26
【问题描述】:
我希望能够使用 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() 并返回结果。
【问题讨论】:
-
您可以尝试使用
returns(Either[ErrorCode, T])()而不是onCall。嗯,我需要运行它来尝试解决它。
标签: scala unit-testing scalamock