本文介绍了如何使用ScalaMock模拟按名称调用参数(如getOrElse)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够模拟getOrElse
方法的返回值,以便它返回通过ScalaMock作为orElse
调用名称参数传递的内容
I'd like to be able to mock a return value of getOrElse
method so that it returns what is passed as orElse
call-by-name argument with ScalaMock
trait ToBeMocked {
def getOrElse(arg: Int)(orElse: => String): String
}
必须使用ScalaMock,因为它会引起混乱.运行此:
ScalaMock has to be used because of currying. Running this:
class CallByNameMockSpec extends Specification with MockFactory {
trait ToBeMocked {
def getOrElse(arg: Int)(orElse: => String): String
}
"Mocking functions with call-by-name arguments" should {
"work" in {
val m = mock[ToBeMocked]
(m.getOrElse (_: Int)(_: String)).expects(101, *).onCall((x, y) => y)
m.getOrElse(101)("result") must beEqualTo("result")
}
}
}
引发异常:
[error] ClassCastException:
test.service.CallByNameMockSpec$$anonfun$1$$anonfun$apply$1$$anonfun$apply$3$$anonfun$apply$4 cannot be cast to java.lang.String (CallByNameMockSpec.scala:16)
推荐答案
诀窍是使用onCall
方法的Product
版本,将第二个参数转换为() => String
并调用它:
The trick is to use Product
version of onCall
method, convert the second argument to () => String
and call it:
class CallByNameMockSpec extends Specification with MockFactory {
trait ToBeMocked {
def getOrElse(arg: Int)(orElse: => String): String
}
"Mocking functions with call-by-name arguments" should {
"work" in {
val m = mock[ToBeMocked]
(m.getOrElse (_: Int)(_: String)).expects(101, *).onCall(_.productElement(1).asInstanceOf[() => String]())
m.getOrElse(101)("result") must beEqualTo("result")
}
}
}
这篇关于如何使用ScalaMock模拟按名称调用参数(如getOrElse)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!