【问题标题】:Mocking the sort method from Collections模拟集合中的排序方法
【发布时间】:2014-07-15 11:06:34
【问题描述】:

我有一个要进行单元测试的代码。该代码使用Collections.sort 方法为它提供我们自己的甜蜜比较器,例如:

List<Something> something = somethingService.doSomething(someParameter);
Collections.sort(something, somethingComparator);

现在在测试函数时,我正在模拟 somethingService 并存根 doSomething 方法,例如:

List<Something> mockList = Mockito.mock(List.class); 
Mockito.when(somethingService.doSomething(anyInt())).thenReturn(mockList);

我将 Collections 嘲笑为:

PowerMockito.mockStatic(Collections.class);
PowerMockito.doNothing().when(Collections.class, "sort", anyListOf(Something.class), anyOf(Comparator.class));

但它给了我:

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected
You cannot use argument matchers outside of verification or stubbing.

现在我知道,如果我们在函数的任何参数中使用参数匹配器,我们需要为所有参数提供匹配器。但是这里有可能做同样的事情,如果没有,那么现有的解决方法是什么?

【问题讨论】:

  • @Community : 请帮忙:)
  • 这很奇怪。我遇到同样的问题。但是这个similar answer 有效
  • @Gontard :我也尝试了网络上可用的大多数解决方法,但都是徒劳的。我什至尝试过间谍活动,但他们又提出了一个不同的问题。现在我能想到的只是他提供了假货而不是模拟,并使单元测试用例运行。
  • 是的,您可以避免模拟列表并存根排序方法。
  • 为什么还需要模拟集合?你到底在测试什么?

标签: java unit-testing junit mockito powermock


【解决方案1】:

您正在使用 PowerMock 模拟来自 JDK 的 系统类,在设计方面它真的非常非常讨厌。真的应该像作者本人一样认真考虑他的motivation to use Powermock

Powermock 不能真正直接模拟来自系统类的静态方法,您必须围绕系统调用创建 包装器,如 wiki 中所述。

我强烈建议您提取一些排序策略,您可以仅使用 Mockito 进行模拟。

【讨论】:

  • 维基条目展示了如何模拟URLEncoder。那么为什么它不适用于 Collections 呢?
  • 我认为您需要结束通话。但是,如果没有完整的代码,我们无法帮助您诊断更多信息。
猜你喜欢
  • 1970-01-01
  • 2017-06-03
  • 1970-01-01
  • 1970-01-01
  • 2012-01-03
  • 1970-01-01
  • 2020-11-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多