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.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s