0

I am new to writing unit test cases in Java and I am trying to figure out how I should mock my test cases for my http client. I am trying to test the following function:

public HttpResponse getRequest(String uri) throws Exception {
        String url = baseUrl + uri;

        CloseableHttpClient httpClient =  HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
        get.setHeader(AUTHORIZATION_HEADER, authorization);
        get.setHeader(ACCEPT_HEADER, APPLICATION_JSON);
        HttpResponse response = httpClient.execute(get);
        return response;
    }

I don't want to actually call the url and hit the server, I just want to try mock all the responses which I can get from the server, such as 500 or 200 or socket errors. I have looked into Mockito library to mock java functions, but I have read that Mockito cant be used for static methods.

Could someone guide me on how I should write a unit test for this? Also since httpClient is being created inside the function, is this a good practice for testing ?

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • 2
    Can you please elaborate about how your question is different from [your previous one here](http://stackoverflow.com/q/40496322/1426891)? – Jeff Bowman Nov 16 '16 at 04:19

1 Answers1

0

You cannot mock the HttpClient in this case since you are creating it inside the method which is not recommended, instead you should inject your dependencies in this case HttClient.

Below is code :

public class Test1 {
    private HttpClient httpClient ;
    Test1(HttpClient httpClient){
        this.httpClient = httpClient;
    }

    public HttpResponse getRequest(String uri) throws Exception {
        HttpGet get = new HttpGet(uri);
        HttpResponse response = httpClient.execute(get);
        return response;
    }
}

Test Class

public class Test1Test {

    @Test
    public void testGetRequest() throws Exception {
        final HttpClient mockHttpClient = Mockito.mock(HttpClient.class);
        final Test1 test1 = new Test1(mockHttpClient);
        final HttpResponse mockHttpResponse = Mockito.mock(HttpResponse.class);
        final StatusLine mockStatusLine = Mockito.mock(StatusLine.class);
        Mockito.when(mockHttpClient.execute(ArgumentMatchers.any(HttpGet.class))).thenReturn(mockHttpResponse);
        Mockito.when(mockHttpResponse.getStatusLine()).thenReturn(mockStatusLine);
        Mockito.when(mockStatusLine.getStatusCode()).thenReturn(200);
        final HttpResponse response = test1.getRequest("https://url");
        assertEquals(response.getStatusLine().getStatusCode(), 200);
    }
}
Liju John
  • 1,749
  • 16
  • 19