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:
def myMethod(param: String, defaultStr: String = "defaultToThis")
and you try to mock it thusly:
when(mocked.myMethod(anyString))
you’ll probably be met with the following complaint from Mockito:
[info] org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
[info] 0 matchers expected, 2 recorded.
[info] This exception may occur if matchers are combined with raw values:
[info] //incorrect:
[info] someMethod(anyObject(), "raw String");
[info] When using matchers, all arguments have to be provided by matchers.
[info] For example:
[info] //correct:
[info] someMethod(anyObject(), eq("String by matcher"));
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:
when(mocked.myMethod(anyString, anyString))
or if you want to be more specific (and generally you should):
when(mocked.myMethod(anyString, Matchers.eq("defaultToThis")))
(This highlights another gotcha. eq is a method on AnyRef so it hides any static import of Matchers.eq).
























