Consider a method signature like:
public String myFunction(String abc);
Can Mockito help return the same string that the method received?
Mockito allows us to partially mock an object. This means that we can create a mock object and still be able to call a real method on it. To call a real method on a mocked object we use Mockito's thenCallRealMethod().
Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.
To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).
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]);
If you have Mockito 1.9.5 or higher, there is a new static method that can make the Answer
object for you. You need to write something like
import static org.mockito.Mockito.when; import static org.mockito.AdditionalAnswers.returnsFirstArg; when(myMock.myFunction(anyString())).then(returnsFirstArg());
or alternatively
doAnswer(returnsFirstArg()).when(myMock).myFunction(anyString());
Note that the returnsFirstArg()
method is static in the AdditionalAnswers
class, which is new to Mockito 1.9.5; so you'll need the right static import.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With