【问题标题】:mocking generic method using Mockito and Scala使用 Mockito 和 Scala 模拟泛型方法
【发布时间】:2017-07-25 17:45:02
【问题描述】:

我正在尝试在 Finatra HttpClient 中为以下函数编写测试。

def executeJson[T: Manifest](
    request: Request,
    expectedStatus: Status = Status.Ok): Future[T] = {...}

根据 StackOverflow 上回答的另一个问题。 mocking generic scala method in mockito。这是以下的简写:

def executeJson[T](
    request: Request, 
    expectedStatus: Status = Status.Ok)
    (implicit T: Manifest[T]): Futuren[T] = {...}

所以我尝试了,

verify(httpClientMock, times(1)).executeJson[JiraProject]
    (argThat(new RequestMatcher(req)))(Matchers.any())

很遗憾,它并没有解决我的问题。我仍然收到以下错误。

Invalid use of argument matchers!
0 matchers expected, 1 recorded:
-> at org.specs.mock.MockitoStubs$class.argThat(Mockito.scala:331)

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

我也试过Matchers.eq(Manifest[JiraProject]),它抱怨value Manifest of type scala.reflect.ManifestFactory.type does not take type parameters

我是 Scala 和 Mockito 的新手,有什么我做错或误解了吗?

提前感谢您的帮助!


发现问题了!所以 executeJson 实际上需要 3 个参数——request、expectedStatus 和 Manifest。但是,因为 expectedStatus 是可选的,所以我没有明确传递它,这就是它抱怨的原因。所以,最终的代码应该是verify(httpClientMock, times(1)).executeJson[JiraProject](argThat(new RequestMatcher(req)), Matchers.any[Status])(Matchers.any())

【问题讨论】:

    标签: scala unit-testing generics mockito


    【解决方案1】:

    您的问题是您在第一个参数中使用相等,而在第二个参数中使用匹配器。尝试对所有参数使用匹配器。

    但我觉得这里的一个更大的问题是您正在尝试模拟 3rd 方库 - 这是您应该避免的事情。这也可以解决您的问题。这里有一些关于它的额外阅读 - TDD best practices: don't mock others

    【讨论】:

    • 是的,我认为你是对的,我应该避免嘲笑 3rd 方库。
    猜你喜欢
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-01
    相关资源
    最近更新 更多