以下是我尝试运行的代码:
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")
}
}
}
运行时,我收到以下错误:
[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"));
这会有很大意义,但是当我收到错误时,eq("my err msg")
和equals("my err msg")
都不能完成工作。我错过了什么?
答案 0 :(得分:6)
我想补充一点,你应该警惕默认参数,即如果在存根方法时使用匹配器,请确保为所有参数传递参数匹配器,因为默认参数几乎肯定会有常量值 - 导致出现同样的错误。
E.g。存根方法
def myMethod(arg1: String, arg2: String arg3: String = "default"): String
你不能简单地做
def myMethod(anyString, anyString) returns "some value"
但你还需要传递一个参数匹配器来获取默认值,如下所示:
def myMethod(anyString, anyString, anyString) returns "some value"
失去了半个小时搞清楚这一点:)
答案 1 :(得分:5)
当您使用匹配器匹配参数时,您必须将它们用于所有参数。正如all arguments have to be provided by matchers
所示。
此外,如果您使用specs2
匹配器,则需要强类型化。 equals
是Matcher[Any]
,但Matcher[Any]
尚未转换为String
method
接受的转化。
因此,您需要Matcher[T]
或Matcher[String]
。如果您只想测试相等性,则强类型匹配器为===
there was no(logger).error(any[Exception], ===("hey"))