How to mock a dynamic value returned from a method with Mockito?

Probably, most of you already know this, but it is good to keep it in mind when you want to dynamically change the values returned by a mock you have.

doAnswer(invocation -> {
            RestCallback restCallback = (RestCallback) invocation.getArguments()[0];
            return null;

The most important things here are:
– doAnswer – method that accepts the invocation from which you can get the actual arguments and mock the return value
– when – method that is used on the mocked instance and does the magic to return whatever you want

Another way to mock the returned value is to use:


which actually verifies that the mApi.getSchedule was called with the NODE_ID constant.

You may also like...