Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

org.specs2.mock.Mockito matchers are not working as expected

Here is the code I am trying to run:

import org.specs2.mock.Mockito
import org.specs2.mutable.Specification
import org.specs2.specification.Scope
import akka.event.LoggingAdapter

class MySpec extends Specification with Mockito {


  "Something" should {
      "do something" in new Scope {

      val logger = mock[LoggingAdapter]

      val myVar = new MyClassTakingLogger(logger)

      myVar.doSth()

      there was no(logger).error(any[Exception], "my err msg")
      }
  }

}

When running this, I get the following error:

[error]    org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
[error]    Invalid use of argument matchers!
[error]    2 matchers expected, 1 recorded:
[error]    -> at         org.specs2.mock.mockito.MockitoMatchers$class.any(MockitoMatchers.scala:47)
[error]
[error]    This exception may occur if matchers are combined with raw values:
[error]        //incorrect:
[error]        someMethod(anyObject(), "raw String");
[error]    When using matchers, all arguments have to be provided by matchers.
[error]    For example:
[error]        //correct:
[error]        someMethod(anyObject(), eq("String by matcher"));

Which would make a lot of sense, but neither eq("my err msg") nor equals("my err msg") does the job as I get an error. What am I missing?

like image 853
eddyP23 Avatar asked Oct 17 '25 08:10

eddyP23


2 Answers

I would like to add that you should be wary of default arguments, i.e. if using matchers when stubbing methods, make sure to pass argument matchers for all arguments, because default arguments will almost certainly have constant values - causing this same error to appear.

E.g. to stub the method

def myMethod(arg1: String, arg2: String arg3: String = "default"): String

you cannot simply do

def myMethod(anyString, anyString) returns "some value"

but you also need to pass an argument matcher for the default value, like so:

def myMethod(anyString, anyString, anyString) returns "some value"

Just lost half an hour figuring this out :)

like image 177
Zoltán Avatar answered Oct 19 '25 23:10

Zoltán


When you are using matchers to match parameters you have to use them for all parameters. as the all arguments have to be provided by matchers indicates.

Moreover if you use a specs2 matcher it needs to be strongly-typed. equals is a Matcher[Any] but there is no conversion from Matcher[Any] to a String which is what method accepts.

So you need a Matcher[T] or a Matcher[String] in your case. If you just want to test for equality, the strongly-typed matcher is ===

there was no(logger).error(any[Exception], ===("hey"))
like image 22
Eric Avatar answered Oct 19 '25 22:10

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!