Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a mocked method return an argument that was passed to it

Tags:

java

mockito

Consider a method signature like:

public String myFunction(String abc); 

Can Mockito help return the same string that the method received?

like image 305
Abhijeet Kashnia Avatar asked Apr 21 '10 16:04

Abhijeet Kashnia


People also ask

Is it possible to call the actual methods after mocking a class?

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().

What is method mocking?

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.

How do you know if mocked method called?

To check if a method was called on a mocked object you can use the Mockito. verify method: Mockito. verify(someMock).


2 Answers

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]); 
like image 178
Steve Avatar answered Sep 21 '22 03:09

Steve


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.

like image 22
Dawood ibn Kareem Avatar answered Sep 21 '22 03:09

Dawood ibn Kareem