仿真回调和获取参数值

我没有任何运气让 Mockito 捕获函数参数值!我正在模仿一个搜索引擎索引,而不是建立一个索引,我只是使用散列。

// Fake index for solr
Hashmap<Integer,Document> fakeIndex;


// Add a document 666 to the fakeIndex
SolrIndexReader reader = Mockito.mock(SolrIndexReader.class);


// Give the reader access to the fake index
Mockito.when(reader.document(666)).thenReturn(document(fakeIndex(666))

我不能使用任意的参数,因为我正在测试查询的结果(即它们返回的文档)。同样,我也不想为每个文档指定一个特定的值,并且每个文档都有一行!

Mockito.when(reader.document(0)).thenReturn(document(fakeIndex(0))
Mockito.when(reader.document(1)).thenReturn(document(fakeIndex(1))
....
Mockito.when(reader.document(n)).thenReturn(document(fakeIndex(n))

我查看了 用 Mockito页面上的回调部分。不幸的是,它不是 Java,我不能得到我自己的解释在 Java 中工作。

编辑(澄清) : 如何让 Mockito 捕获一个参数 x 并将其传递给我的函数?我想要传递给函数的 X 的确切值(或 ref)。

我不想枚举所有的情况,任意的参数不会起作用,因为我正在为不同的查询测试不同的结果。

Mockito 网页上说

val mockedList = mock[List[String]]
mockedList.get(anyInt) answers { i => "The parameter is " + i.toString }

这不是 java,而且我不知道如何将其转换成 java 或者将发生的任何事情传递给函数。

103120 次浏览

I've never used Mockito, but want to learn, so here goes. If someone less clueless than me answers, try their answer first!

Mockito.when(reader.document(anyInt())).thenAnswer(new Answer() {
public Object answer(InvocationOnMock invocation) {
Object[] args = invocation.getArguments();
Object mock = invocation.getMock();
return document(fakeIndex((int)(Integer)args[0]));
}
});

Check out ArgumentCaptors:

https://site.mockito.org/javadoc/current/org/mockito/ArgumentCaptor.html

ArgumentCaptor<Integer> argument = ArgumentCaptor.forClass(Integer.class);
Mockito.when(reader.document(argument.capture())).thenAnswer(
new Answer() {
Object answer(InvocationOnMock invocation) {
return document(argument.getValue());
}
});

With Java 8, this could be something like this:

Mockito.when(reader.document(anyInt())).thenAnswer(
(InvocationOnMock invocation) -> document(invocation.getArguments()[0]));

I am assuming that document is a map.

You might want to use verify() in combination with the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<Document> argument = ArgumentCaptor.forClass(Document.class);
verify(reader).document(argument.capture());
assertEquals(*expected value here*, argument.getValue());

The argument's value is obviously accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.