我试图嘲弄一个方法调用,需要一个呼叫按姓名参数:如何在Scala中模拟具有函数参数的方法?
import org.scalatest.WordSpec
import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._
import org.junit.runner.RunWith
import org.scalatest.junit.JUnitRunner
trait Collaborator {
def doSomething(t: => Thing)
}
trait Thing
@RunWith(classOf[JUnitRunner])
class Test extends WordSpec with MockitoSugar {
"The subject under test" should {
"call the collaborator" in {
// setup
val m = mock[Collaborator]
val t = mock[Thing]
// test code: this would actually be invoked by the SUT
m.doSomething(t)
// verify the call
verify(m).doSomething(t)
}
}
}
我在主要的Mockito感兴趣,因为这就是我使用的是什么,但我有兴趣看看任何主要的模拟框架是否有能力进行这种测试。测试失败在上verify
线运行时,用这样的错误
Argument(s) are different! Wanted: collaborator.doSomething( ($anonfun$apply$3) <function> ); -> at Test$$anonfun$1$$anonfun$apply$1.apply(Test.scala:27) Actual invocation has different arguments: collaborator.doSomething( ($anonfun$apply$2) <function> ); -> at Test$$anonfun$1$$anonfun$apply$1.apply(Test.scala:24)
如果我理解正确的情况下,编译器隐含在返回t
一个无参函数包装t
。模拟框架然后将该功能与测试代码中生成的功能进行比较,该功能等效但不是equals()
。
我的情况是一个相对简单的问题,但我认为这是任何高阶函数的问题。
我不明白这与Apple iPad的关系。 – 2010-01-28 05:58:55
您能否描述它如何更清晰地工作或包含一些测试代码?只需显示验证,就很难知道这里发生了什么。 – 2010-01-28 14:49:35
我将这个示例按照书面形式运行,并包含与失败相关的实际输出。 – 2010-01-28 20:56:13