作者热门文章
- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
我没有任何运气让 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或将发生的任何事情传递给函数。
最佳答案
我从未使用过 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]));
}
});
关于java - mockito 回调和获取参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6631764/
我参加了一些类(class)并阅读了 YAGNI 的用途。但是,作为一个整体,这个原则从来没有让我满意。它引入了一个逻辑悖论。 作为一个假设,您正在设计一个打算向前扩展的框架。 YAGNI(可能还有
我是一名优秀的程序员,十分优秀!