mockito回调和获取参数值 [英] mockito callbacks and getting argument values
问题描述
我没有运气让Mockito捕获函数参数值!我正在嘲笑搜索引擎索引,而不是构建索引,我只是使用哈希。
I'm not having any luck getting Mockito to capture function argument values! I am mocking a search engine index and instead of building an index, I'm just using a hash.
// 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))
我不能使用任意参数,因为我正在测试查询结果(即他们返回哪些文件)。同样,我不喜欢我想为每个文档指定一个特定的值并有一行!
I can't use arbitrary arguments because I'm testing the results of queries (ie which documents they return). Likewise, I don't want to specify a specific value for and have a line for each document!
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))
I查看使用Mockito 页面上的回调部分。不幸的是,它不是Java和我无法对Java工作进行自己的解释。
I looked at the callbacks section on the Using Mockito page. Unfortunately, it isn't Java and I couldn't get my own interpretation of that to work in Java.
编辑(澄清):
如何让Mockito获取参数X和传递它进入我的功能?我希望传递给函数的X的确切值(或ref)。
EDIT (for clarification): How do I get get Mockito to capture an argument X and pass it into my function? I want the exact value (or ref) of X passed to the function.
我不想枚举所有情况,任意参数都不起作用,因为我' m测试不同查询的不同结果。
I do not want to enumerate all cases, and arbitrary argument won't work because I'm testing for different results for different queries.
Mockito页面说
The Mockito page says
val mockedList = mock[List[String]]
mockedList.get(anyInt) answers { i => "The parameter is " + i.toString }
这不是java,我不知道怎么做转换成java或传递给函数发生的任何事情。
That's not java, and I don't know how to translate into java or pass whatever happened into a function.
推荐答案
我从未使用过Mockito,但想学习,所以开始。如果有人比我不了解答,请先试试他们的答案!
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]));
}
});
这篇关于mockito回调和获取参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!