我想为此方法编写一个单元测试:
public class ClassToTest {
public boolean initIndex(String url) {
try (CloseableHttpClient client = HttpClients.createDefault()) {
URIBuilder uriBuilder = new URIBuilder(url);
HttpGet httpGet = new HttpGet(uriBuilder.build());;
try (CloseableHttpResponse response = client.execute(httpGet)) {
HttpEntity responseEntity = response.getEntity();
int status = response.getStatusLine().getStatusCode();
EntityUtils.consume(responseEntity);
return status == HttpStatus.SC_OK;
}
} catch (IOException | URISyntaxException ex) {
}
}
}
我的单元测试在这里try (CloseableHttpResponse response = client.execute(httpGet))
不允许我重写此方法/类。
我现在的测试:
public class UnitTestClass {
@InjectMocks
private ClassToTest classToTest;
@Test
public void testInitIndex() throws Exception {
classToTest.initIndex();
}
}
有什么主意吗?
答案 0 :(得分:0)
对于您的情况,要模拟静态方法,可以将EasyMock用于HttpClients.createDefault(),然后返回模拟客户端以验证行为。