我想通过基于网址返回不同的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")});
提前致谢。
答案 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)});
希望这有帮助。