Mockito mock a method but use its parameters for the mocked return

xetra11 picture xetra11 · Jun 22, 2016 · Viewed 11.4k times · Source

There is a method public Content createChild(String path, String contentType, Map<String,Object> properties) I'd like to mock.

I want to mock it that way that the method is called with any kind of arguments, therefore when() wouldn't work because I have to tell it what arguments the method should receive to be actually mocked.

So I want to actually react on any method call independent of its given arguments (use spies?) and then call some kind of "callback" to return a Content object which I want build together out of the real arguments given to the method.

I could not find a specific API in Mockito which supports this.

Answer

thegauravmahawar picture thegauravmahawar · Jun 22, 2016

You can use Matchers:

You can try something like:

when(service.createChild(anyString(), anyString(), anyMap()))
     .thenReturn(any(Content.class));