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)
提前致谢。
您需要一个自定义参数匹配器。
所以在你的测试类中是这样的:
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)
希望这可以帮助。
归档时间: |
|
查看次数: |
902 次 |
最近记录: |