問題描述
我沒有任何運氣讓 Mockito 捕獲函數(shù)參數(shù)值!我正在模擬搜索引擎索引,而不是構(gòu)建索引,我只是使用哈希.
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))
我不能使用任意參數(shù),因為我正在測試查詢的結(jié)果(即它們返回哪些文檔).同樣,我不想為每個文檔指定一個特定的值并有一行!
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))
我查看了 使用 Mockito 頁面上的回調(diào)部分.不幸的是,它不是 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 捕獲參數(shù) X 并將其傳遞給我的函數(shù)?我想將 X 的確切值(或引用)傳遞給函數(shù).
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.
我不想枚舉所有情況,并且任意參數(shù)將不起作用,因為我正在測試不同查詢的不同結(jié)果.
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或?qū)l(fā)生的任何事情傳遞給函數(shù).
That's not java, and I don't know how to translate into java or pass whatever happened into a function.
推薦答案
我沒用過 Mockito,但是想學(xué),就這樣吧.如果有人比我不知道答案,請先嘗試他們的答案!
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]));
}
});
這篇關(guān)于mockito 回調(diào)和獲取參數(shù)值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!