2011-07-08 39 views
48

我没有任何运气让Mockito捕获函数参数值!我嘲笑搜索引擎索引,而不是建立一个索引,我只是使用散列。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)) 

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

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

我不想枚举所有情况下,任意参数将无法正常工作,因为我正在测试针对不同查询的不同结果。

该页面的Mockito说

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

这不是java的,我不知道怎么翻译成Java或通过不管发生什么事情到一个函数。

+0

我不确定我完全理解什么是你的失败。你调用'Mockito.when(reader.document(666))。然后返回(document(fakeIndex(666))'应该为你设置模拟对象。当你调用'reader.document(666)'时?' – highlycaffeinated

+0

666可以正常工作,但是我希望能够传入特定数字X并获得fakeIndex(X)的结果。我有大量潜在文档可用于测试查询,并且我不想输入全部 – nflacco

回答

60

我从来没有使用Mockito,但想学习,所以在这里。如果有人比我更无力回答,请先回答他们的问题!

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])); 
    } 
}); 
+2

我刚刚注意到[Mockito:如何让一个方法返回一个传递给它的参数]的链接(http://stackoverflow.com/questions/2684630/mockito-how-to -make-a-method-return-an-argument-that-was-passed-to-it)看起来我很接近,如果没有发现的话 –

+0

强烈的用户口碑(666)很好。只是我做的东西编译的东西被公开在对象的答案(InvocationOnMock调用)之前...... – nflacco

40

退房ArgumentCaptors:

http://site.mockito.org/mockito/docs/1.10.19/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()); 
    } 
    }); 
+1

哇,我不知道你可以使用'ArgumentCaptor'作为stubbing。尽管如此,这个链接还是有一个很大的警告。谨慎行事。 – einnocent

+2

是的,你说得对。 Captors只能用于验证。 – qualidafial

4

使用Java 8,这可能是这样的:

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

我假设document是地图。

11

您可能需要组合使用验证()与ArgumentCaptor,以确保在测试执行和ArgumentCaptor评估参数:

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

该参数的值是通过argument.getValue明显访问( )进一步操作/检查或任何你想做的事情。