Return an argument passed to a method with Mockito using Answer
Assuming you want to test this class
public class MainService { private MyService myService; public String doStuff(String value) { return myService.doStuff(value); } }
where MyService
has the following implementation
public class MyService { public String doStuff(String value) { return "some string"; } }
If you want mock method doStuff
of class MyService
to return the same value of the input parameter you can do the following:
import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.aptar.mes.service.MainService; import com.aptar.mes.service.MyService; @RunWith(MockitoJUnitRunner.class) public class SpringTestApplicationTests { @InjectMocks private MainService mainService; @Mock private MyService myService; @Test public void doStuffTest() throws Exception { when(myService.doStuff(anyString())).thenAnswer(invocation -> { return invocation.getArgument(0); }); assertEquals("hello", mainService.doStuff("hello")); } }
Answer
is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.
Below an example of test