1

I'm using Mockito and I'm in a weird situation where I've to authenticate a client and then make an actual API call using the same code:

//@Mock //I want to mock this only for authentication
CloseableHttpClient httpClient;

 //when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(someResponse);

response = httpClient.execute(httpUriRequest);

Now I want to use the actual httpClient object for Authentication and Mocked httpClient object for the actual API call. How can I achieve this requirement?

vaibhav
  • 3,929
  • 8
  • 45
  • 81
gkaka
  • 61
  • 1
  • 6
  • 1
    Why do you need to do that? Are you testing the authentication or the API call? If you are testing the authentication, why do you need to make the call? Could be an https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem – Bentaye Mar 04 '20 at 14:32

1 Answers1

0

Thank you, everyone, for your response.

I solved the problem with Mockito.spy().

Dropping my solution if anyone finds it helpful in the future.

    @Test
    public void myTest(){

    //This object will be a normal instance
    CloseableHttpClient httpClient;

    //Authentication: /oauth/token
    //response is real because httpClient is an actual instance.
    response = httpClient.execute(httpUriRequest);

    CloseableHttpClient spyHttpClient = Mockito.spy(httpClient);
    doReturn(mockedCloseableHttpResponse).when(spyHttpClient).execute(any(HttpUriRequest.class));

    //Actual API call: /v1/users
    //response is mockedCloseableHttpResponse because httpClient is a spy instance.
    response = httpClient.execute(httpUriRequest);

    //Assertion code here

    }

Here is more details about mockito-spy: Mockito – Using Spies

gkaka
  • 61
  • 1
  • 6