mockito 回调和获取参数值

mockito callbacks and getting argument values(mockito 回调和获取参数值)

本文介绍了mockito 回调和获取参数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

我查看了 使用 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 的确切值(或引用)传递给函数.

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.

我不想枚举所有情况,并且任意参数将不起作用,因为我正在测试不同查询的不同结果.

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 回调和获取参数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:mockito 回调和获取参数值

基础教程推荐