One way could be to avoid too restrictive arguments to provide the expected results with just one thenReturn
call.
For example, let's say that I want to mock this method:
public String foo(String firstArgument, Object obj) { return "Something"; }
Then you can mock him by providing as many results as you want:
// Mock the call of foo of any String to provide 3 results when(mock.foo(anyString(), anyObject())).thenReturn("val1", "val2", "val3");
Calling foo
with any parameters will give " val1
", " val2
", respectively, then any subsequent calls will contain " val3
".
In case you care about the passed values, but do not want to depend on the sequence of calls, you can use thenAnswer
to provide an answer that matches the second argument, as it is currently, but with 3 different thenReturn
.
when(mock.foo(anyString(), anyObject())).thenAnswer( invocation -> { Object argument = invocation.getArguments()[1]; if (argument.equals(new ARequest(1, "A"))) { return new AResponse(1, "passed"); } else if (argument.equals(new ARequest(2, "2A"))) { return new AResponse(2, "passed"); } else if (argument.equals(new BRequest(1, "B"))) { return new BResponse(112, "passed"); } throw new InvalidUseOfMatchersException( String.format("Argument %s does not match", argument) ); } );
source share