如何构建com.netflix.client.http.httpresponse对象

时间:2017-01-11 04:32:15

标签: unit-testing mocking httpresponse spock netflix

我正在撰写unit test个案例,使用mocking概念,我mocking RestClient class 原始代码:

final HttpResponse response = restClient.executeWithLoadBalancer(request);

Spock中的测试类模拟代码:

restClient.executeWithLoadBalancer(_ as HttpRequest) >> httpResponse

这里我必须构建并设置httpResponse。如何构建HttpResponse

1 个答案:

答案 0 :(得分:2)

由于HttpResponse是一个接口,您无法真正构建或创建它的实例。您可以做的就是创建实现此接口的类的实例。例如:HttpClientResponse

您可以构建和设置httpResponse  你喜欢的任何东西,如下,

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

在旁注上,要模拟ClientResponse,您需要在类路径中使用objenesis