【发布时间】: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