【问题标题】:Problem with mockito matchers when i run my tests运行测试时模拟匹配器出现问题
【发布时间】:2021-02-09 09:30:20
【问题描述】:

我是 Mockito 的新手,我正在处理匹配器的一个非常奇怪的问题

def fetchById[T: Format](elasticDetails: ESDetails): F[ESResult[T]]

我的弹性搜索客户端有这个定义,问题从我必须通过的通用格式开始。

        .fetchById[JsValue](anyObject[ESDetails])
        .returns(IO.pure(ESResult(200, value = Some(fakeResponse)))) ```



org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 1 recorded:
-> at org.specs2.mock.mockito.MockitoMatchers.anyObject(MockitoMatchers.scala:49)

This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));```


//This the error for matchers that i'm getting after I run my tests.

【问题讨论】:

  • fetchById 接受两个参数,看看 T: Format 去糖的内容。另外,不要在 Scala 中使用 mockito,如果你真的无法避免 mock,scalamock 会更好。

标签: scala mockito matcher


【解决方案1】:

您正在隐式传递Format[T] 的真实实例以及ESDetails 的假Matcher 实例。 Mockito 要求所有参数都是真实实例或匹配器,并且不允许您混合它们,正如您从该错误消息中看到的那样。

最简单的解决方法是将隐式参数转换为匹配器,例如

.fetchById[JsValue](anyObject[ESDetails])(eq(implicitly[Format[T]]))

另见What precisely is a scala evidence parameterHow to stub a method call with an implicit matcher in Mockito and Scala

正如 Mateusz 所说,使用 scalamock 可能比使用 Mockito 更好,因为它是为 Scala 设计的,因此可以更好地处理这种情况。

【讨论】:

    猜你喜欢
    • 2012-01-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多