gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 08:41:56 25 4
gpt4 key购买 nike

我想通过基于 url 返回不同的 CloseableHttpResponse 对象来模拟一个行为。对于 URL1 我想给出 302 响应,对于 url2 我想给出 200 ok 响应。本次测试的方法以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")});

提前致谢。

最佳答案

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

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

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)});

希望这对您有所帮助。

关于java - 匹配被测方法内部创建的HttpGet对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39491822/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com