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 -> {
            @SuppressWarnings("unchecked")
            RestCallback restCallback = (RestCallback)  invocation.getArguments()[0];
            restCallback.onSuccess(null);
            return null;
        }).when(mApi).updateNode(Matchers.anyObject(),
                any(NodeEntity.class),
                eq(NODE_ID))


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:

verify(mApi).getSchedule(NODE_ID);

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:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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