Search code examples
unit-testingmockinghttpresponsespocknetflix

how to build com.netflix.client.http.httpresponse object


I am writing unit test cases, using mocking concept, I am mocking RestClient class original code:

final HttpResponse response = restClient.executeWithLoadBalancer(request);

Test class mock code in Spock:

restClient.executeWithLoadBalancer(_ as HttpRequest) >> httpResponse

here I have to build and set httpResponse. How to build HttpResponse


Solution

  • As HttpResponse is an interface and you can't really build or create instance of it.what you can able to do is probably create instance of class that implements this interface. for eg: HttpClientResponse

    and you can build and set httpResponse anything you like as below,

    ClientResponse clientResponse = Mock(ClientResponse)
    MultivaluedMapImpl sampleHeaders = new MultivaluedMapImpl()
    sampleHeaders.add("name", "test")
    clientResponse.getHeaders() >> sampleHeaders
    HttpResponse httpResponse = new HttpClientResponse(clientResponse,null,null)
    
    restClient.executeWithLoadBalancer(_ as HttpRequest) >> httpResponse
    

    on a side note ,to mock ClientResponse you need the objenesis in your classpath.