gpt4 book ai didi

java - mockito 回调和获取参数值

转载 作者:IT老高 更新时间:2023-10-28 13:51:47 25 4
gpt4 key购买 nike

我没有任何运气让 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com