'Mock open feign response body

I have a code as shown

MyDefinition databricksResponseBody = null;
ResponseBody = gson.fromJson(Response.body().asReader(), MyDefinition.class);

Now to mock this I am using Mockito. I already mocked the header of this response but unable to mock the body. Confused about how to achieve that? Tried but failed.

responseMock.headers().put("xxxxxx", headerValues);



Solution 1:[1]

One way is to "chain" mocks by mocking not only the Response, but the internal objects.

/* create the response mock */
Response response = mock(Response.class);

/* create the body mock */
Response.Body body = mock(Response.Body.class);

/* specify that the mocked body should be returned */
when(response.body()).thenReturn(body);

/* more mocking or do something with the response */
...

With this technique, you should be able to manipulate the mocked Body for any of your use cases.

Solution 2:[2]

We cannot mock feign.Response as this is a Final class! Better we should use powerMock else give the own fake implementation.

Solution 3:[3]

To mock a final class or method, you need to add a text file to the project's src/test/resources/mockito-extensions directory named org.mockito.plugins.MockMaker and add a single line of text:

mock-maker-inline

Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.

Then, you should mock your Response as bellow. You can also mock the other fields of response.

Response response = mock(Response.class);
Response.Body body = mock(Response.Body.class);
when(response.body()).thenReturn(body);

More details in this link: https://www.baeldung.com/mockito-final#configure-mocktio

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kevin Davis
Solution 2 Robson
Solution 3