匹配被测方法内部创建的 HttpGet 对象

Bha*_*gat 2 java unit-testing mockito apache-httpclient-4.x

我想通过CloseableHttpResponse基于 url返回不同的对象来模拟行为。因为URL1我想给出302回应,因为url2我想给出200确定的回应。此测试下的方法将url作为输入并在HttpGet内部创建一个请求对象并使用httpresponse对象执行某些操作。但我无法匹配这个HttpGet论点。有什么办法可以测试这个方法。PShttpClient也是一个模拟对象。以下代码不起作用,因为期望无法模拟 new 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")});
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Tay*_*lor 5

您需要一个自定义参数匹配器

所以在你的测试类中是这样的:

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));
}
Run Code Online (Sandbox Code Playgroud)

如果您需要在多个测试类中,上述内容也可以驻留在一些测试 utils 类中。在这种情况下,该方法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)});
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。

  • 它与一个匹配器一起正常工作。虽然我陷入了第二个问题。当我尝试为 URL2 设置期望时,它开始给我空指针异常。在此页面上解决 http://stackoverflow.com/questions/13846837/using-multiple-argumentmatchers-on-the-same-mock?rq=1 (2认同)