Search code examples
mockingmockitospecs2callbyname

`answers` is not invoked when mocking a method with `call-by-name` parameter


There is a class InvokeLater, the definition is like:

class InvokeLater {
    def apply(f: => Any): Unit = { 
       // do something ...
       f 
       // do some other thing
    }
}

In specs test, I mocking it like:

val invokeLater = mock[InvokeLater]
invokeLater.apply(any) answers { f => f:Unit }

But it seems the code inside answers never runs.

Does specs2 support this feature now?


Solution

  • First of all you need to make sure that specs2-mock.jar is placed before mockito.jar on your classpath. Then be aware that the f passed to the answers method is a Function0. For example

    class InvokeLater {
      def apply(f: =>Int): Unit = {
        // do something ...
        f
        // do some other thing
      }
    }
    
    val invokeLater = mock[InvokeLater]
    
    invokeLater.apply(any) answers { f =>
      println("got the value "+f.asInstanceOf[Function0[Int]]())
    }
    
    invokeLater.apply(1)
    

    This prints:

    got the value 1