匹配在测试中的方法内部创建的HttpGet对象

时间:2016-09-14 13:31:06

标签: java unit-testing mockito apache-httpclient-4.x

我想通过基于网址返回不同的CloseableHttpResponse对象来模拟行为。对于URL1,我想提供302响应,对于url2,我想提供200个确定回复。此测试下的方法将url作为输入,并在内部创建HttpGet请求对象,并对httpresponse对象执行某些操作。但我无法匹配HttpGet参数。有什么方法可以测试这种方法。附: httpClient也是一个模拟对象。以下代码无效,因为期望无法模拟新的HttpGet(Url)

   CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
    when(httpClient.execute(new HttpGet(URL1))).thenReturn(httpResponse);
    when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("1.1",0,0),HttpStatus.SC_MOVED_PERMANENTLY,""));
    when(httpResponse.getHeaders(HttpHeaders.LOCATION)).thenReturn( new Header[]{new BasicHeader(HttpHeaders.LOCATION, URL2)});

    CloseableHttpResponse httpResponse1 = mock(CloseableHttpResponse.class);
    when(httpClient.execute(new HttpGet(URL2))).thenReturn(httpResponse1);
    when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("1.1",0,0),HttpStatus.SC_OK,""));
    when(httpResponse.getHeaders(HttpHeaders.CONTENT_LENGTH)).thenReturn( new Header[]{new BasicHeader(HttpHeaders.CONTENT_LENGTH, "0")});

提前致谢。

1 个答案:

答案 0 :(得分:3)

您需要自定义参数匹配器

在测试类中有这样的东西:

static class HttpGetMatcher extends ArgumentMatcher<HttpGet> {

    private final URL expected;

    //Match by URL
    public HttpGetMatcher(URL expected) {
        this.expected = expected;
    }

    @Override
    public boolean matches(Object actual) {
        // could improve with null checks
        return ((HttpGet) actual).getURI().equals(expected);
    }

    @Override
    public void describeTo(Description description) {
        description.appendText(expected == null ? null : expected.toString());
    }
}

private static HttpGet aHttpGetWithUriMatching(URI expected){
    return argThat(new HttpGetMatcher(expected));
}

如果您需要多个测试类,上面的内容也可能存在于某些测试工具类中。在这种情况下,方法aHttpGetWithUriMatching将需要公开。

然后在你的测试方法中:

CloseableHttpResponse httpResponse = mock(CloseableHttpResponse.class);
when(httpClient.execute(aHttpGetWithUriMatching(URL1))).thenReturn(httpResponse);
when(httpResponse.getStatusLine()).thenReturn(new BasicStatusLine(new ProtocolVersion("1.1",0,0),HttpStatus.SC_MOVED_PERMANENTLY,""));
when(httpResponse.getHeaders(HttpHeaders.LOCATION)).thenReturn( new Header[]{new BasicHeader(HttpHeaders.LOCATION, URL2)});

希望这有帮助。