如何在Scala中使用函数参数模拟方法?

Aar*_*rup 20 scala mocking

我正在尝试模拟一个带有call-by-name参数的方法调用:

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)
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

我主要对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)  
Run Code Online (Sandbox Code Playgroud)

如果我正确理解了这种情况,那么编译器会隐式包装t在一个返回的nullary函数中t.然后,模拟框架将该函数与测试代码中生成的函数进行比较,这是等效的但不是equals().

我的情况是一个相对简单的问题版本,但我认为这将是任何高阶函数的问题.

Ale*_*xey 10

这看起来很难看,但希望它可以帮助您找到好的解决方案:

import org.scalatest.mock.MockitoSugar
import org.mockito.Mockito._

trait Collaborator {
   def doSomething(t: => Thing)
}

trait Thing

new MockitoSugar {
     // setup
     val m = mock[Collaborator]
     val t = mock[Thing]

     m.doSomething(t)

     classOf[Collaborator].getMethod("doSomething", classOf[Function0[_]]).invoke(
        verify(m), 
        new Function0[Thing] { 
            def apply() = null
            override def equals(o: Any): Boolean = t == o.asInstanceOf[Function0[Thing]].apply() 
      })
}
Run Code Online (Sandbox Code Playgroud)