结果返回模拟方法的参数 [英] Return argument of mocked method as a result
本文介绍了结果返回模拟方法的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最简单的例子:我有以下方法:
The simplest example:I have the following method:
public String testMethod(String arg){
.....
}
我想模拟该方法以返回传递的参数作为结果.例如:
I want to mock this method to return passed argument as a result. For example:
testMethod("aString") returns "aString"
testMethod("anotherString") returns "anotherString"
我知道我可以对这种行为进行硬编码,但是我希望它是通用的.
I know I can hard code this behavior, but I want it generic.
推荐答案
You can write your own Answer
:
when(mock.testMethod(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) {
return invocation.getArgumentAt(0, String.class);
}
});
或者:
when(mock.testMethod(anyString()))
.thenAnswer(AdditionalAnswers.<String>returnsFirstArg());
这篇关于结果返回模拟方法的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文