patternjavaCritical
Making a mocked method return an argument that was passed to it
Viewed 0 times
makingreturnargumentmethodmockedthatpassedwas
Problem
Consider a method signature like:
Can Mockito help return the same string that the method received?
public String myFunction(String abc);Can Mockito help return the same string that the method received?
Solution
Since Mockito 1.9.5+ and Java 8+
You can use a lambda expression, like:
Where
For older versions
You can create an Answer in Mockito. Let's assume, we have an interface named MyInterface with a method myFunction.
Here is the test method with a Mockito answer:
You can use a lambda expression, like:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);Where
i is an instance of InvocationOnMock.For older versions
You can create an Answer in Mockito. Let's assume, we have an interface named MyInterface with a method myFunction.
public interface MyInterface {
public String myFunction(String abc);
}
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
MyInterface mock = mock(MyInterface.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer() {
@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"));
}
Code Snippets
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);Context
Stack Overflow Q#2684630, score: 1447
Revisions (0)
No revisions yet.