本文介绍了如何让方法返回传递给它的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑方法签名,如:
public String myFunction(String abc);
Mockito可以帮助返回方法收到的相同字符串吗?
Can Mockito help return the same string that the method received?
推荐答案
您可以在Mockito中创建答案。假设我们有一个名为Application的接口,其方法为myFunction。
You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.
public interface Application {
public String myFunction(String abc);
}
以下是Mockito答案的测试方法:
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
从Mockito 1.9.5和Java 8开始,使用更简单的方法lambda函数:
Since Mockito 1.9.5 and Java 8 there is an even easier way by using lambda functions:
when(myMock.myFunction(anyString()))。thenAnswer(i - > i.getArguments()[0] );
这篇关于如何让方法返回传递给它的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!