Skip to content
Advertisement

Mocking a Nested Object in Junit

I have a service I am mocking like this:

JavaScript

}

the service:

JavaScript

I need to be able to mock the “CloseableHttpResponse response = httpclient.execute(request, clientContext)”, such that the “response” object is something I create ahead of time. I am hoping some mocking when/then constructs would work for this? I would grateful for ideas on how to do this. Thanks!

Advertisement

Answer

You can’t do it using the current code structure. httpclient object is getting created within the method under test. So it can’t be mocked.

You need to delegate httpclient object creation to another method with belongs to a different class (something similar to HttpClientFactory class). That HttpClientFactory class should only be responsible for creating httpClient instances. If you need you can write separate unit test case for the class.

JavaScript

Now you can mock response like below:

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement