Scala with Mockito gotcha

We do a lot of Scala over at Top10 nowadays.  We also do a lot of unit testing and that means a lot of mocking.  We’ve been using Mockito due to our familiarity with it as Java developers and because Scala’s excellent interoperability with Java means that features like the @Mock annotation still work on Scala objects.

One thing to bear in mind when using Mockito matchers with Scala is that Mockito, being a Java library knows nothing of a Scala method’s default arguments.  So if you have a method like:

and you try to mock it thusly:

you’ll probably be met with the following complaint from Mockito:

You can’t mix regular values with Mockito matchers when mocking a method’s behavior and the default values will be supplied as plain old values to the mockito object.  The only option is to call all the default parameters with matchers:

or if you want to be more specific (and generally you should):

(This highlights another gotcha.  eq is a method on AnyRef so it hides any static import of Matchers.eq).

This entry was posted in Development, Java, Scala and tagged , , , , . Bookmark the permalink.

One Response to Scala with Mockito gotcha

  1. Daniel Bell says:

    Found the solution to the eq problem..

    import org.mockito.Matchers.{eq => mockEq}

    Then you can refer to eq as mockEq, avoiding the warnings

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">