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);
}
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"));
}
Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…