org.specs2.mock.Mockito匹配器未按预期工作

edd*_*P23 2 specifications scala mockito specs2

这是我试图运行的代码:

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")
      }
  }

}
Run Code Online (Sandbox Code Playgroud)

运行此时,我收到以下错误:

[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"));
Run Code Online (Sandbox Code Playgroud)

这会有很大的意义,但是当我得到错误时,既没有eq("my err msg")equals("my err msg")没有工作.我错过了什么?

Zol*_*tán 6

我想补充一点,你应该警惕默认参数,即如果在存根方法时使用匹配器,请确保为所有参数传递参数匹配器,因为默认参数几乎肯定会有常量值 - 导致出现同样的错误.

例如,存根方法

def myMethod(arg1: String, arg2: String arg3: String = "default"): String
Run Code Online (Sandbox Code Playgroud)

你不能简单地做

def myMethod(anyString, anyString) returns "some value"
Run Code Online (Sandbox Code Playgroud)

但是你还需要传递一个参数匹配器来获取默认值,如下所示:

def myMethod(anyString, anyString, anyString) returns "some value"
Run Code Online (Sandbox Code Playgroud)

刚刚失去半小时搞清楚:)


Eri*_*ric 5

使用匹配器匹配参数时,必须将其用于所有参数。如all arguments have to be provided by matchers指示。

此外,如果您使用specs2匹配器,则必须使用强类型。equalsMatcher[Any],但没有从转换Matcher[Any]String这就是method接受。

因此,您需要使用a Matcher[T]或a Matcher[String]。如果您只想测试是否相等,则强类型匹配器为===

there was no(logger).error(any[Exception], ===("hey"))
Run Code Online (Sandbox Code Playgroud)