问题
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?
回答1:
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"))
回答2:
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 :)
来源:https://stackoverflow.com/questions/32441824/org-specs2-mock-mockito-matchers-are-not-working-as-expected