Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to mock a method with functional arguments in Scala?
    primarykey
    data
    text
    <p>I'm trying to mock a method call that takes a call-by-name argument:</p> <pre><code>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: =&gt; 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) } } } </code></pre> <p>I'm primarily interested in Mockito since that's what I'm using, but I'd be interested to see whether any of the major mock frameworks is capable of this kind of testing. The Test fails at runtime on the <code>verify</code> line, with an error like</p> <blockquote> <pre><code>Argument(s) are different! Wanted: collaborator.doSomething( ($anonfun$apply$3) &lt;function&gt; ); -&gt; at Test$$anonfun$1$$anonfun$apply$1.apply(Test.scala:27) Actual invocation has different arguments: collaborator.doSomething( ($anonfun$apply$2) &lt;function&gt; ); -&gt; at Test$$anonfun$1$$anonfun$apply$1.apply(Test.scala:24) </code></pre> </blockquote> <p>If I'm understanding the situation correctly, the compiler is implicitly wrapping <code>t</code> in a nullary function that returns <code>t</code>. The mock framework is then comparing that function to the one produced in the test code, which is equivalent but not <code>equals()</code>.</p> <p>My case is a relatively simple version of the problem, but I think this would be an issue with any higher-order function.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload