cool breeze cool breeze - 1 month ago 9
Scala Question

InvalidUseOfMatchersException when I am passing any string for my mock parameter

I want my mock to be able to handle any input for the method

val redis = mock[RedisClient]
when(redis.scard(any[String])).thenReturn(Some("hello"))


The error:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: Invalid use of argument matchers!
[info] 2 matchers expected, 1 recorded:
[info] -> at ..(SomeSpec.scala:123)
[info]
[info] This exception may occur if matchers are combined with raw values:
[info] //incorrect:
[info] someMethod(anyObject(), "raw String");

Answer

scard takes two parameters, of which one parameter is implicit:

// SCARD
// Return the number of elements (the cardinality) of the Set at key.
def scard(key: Any)(implicit format: Format): Option[Long] =
  send("SCARD", List(key))(asLong)

If you don't specify the argument, Scala will provide one, which interferes with Mockito's ability to line up matchers with arguments.

See also: org.specs2.mock.Mockito matchers are not working as expected