如何模拟junit中的httpclient.newhttpclient()
public String sendAPICall(String portalApiUrl, String reviewAppsAuthKey) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(portalApiUrl + CHECK_ORG_ATT_EXP))
.setHeader(AUTH_REVIEW_API_KEY, reviewAppsAuthKey)
.setHeader(CONTENT_TYPE, APPLICATION_JSON)
.GET()
.build();
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpStatus.OK.value()) {
LOGGER.info(API_SUCCESS);
return API_SUCCESS;
}
} catch (URISyntaxException e) {
LOGGER.error(API_FAIL_URI, e.getMessage());
} catch (InterruptedException e) {
LOGGER.error(API_FAIL_INTER, e.getMessage());
} catch (IOException e) {
LOGGER.error(API_FAIL_IO, e.getMessage());
}
return API_FAILURE;
}
}
junit:
@Test
public void sendAPICallTest() throws IOException, InterruptedException {
Checkorg test = getCheckOrg();
String portalApiUrl = JUNIT_PORTAL_URL;
String reviewAppsAuthKey = JUNIT_AUTH_KEY;
String message = test.sendAPICall(portalApiUrl, reviewAppsAuthKey);
assertEquals(Checkorg.API_SUCCESS, message);
}
如何在测试类中模拟HTTP客户端。
谢谢
public String sendAPICall(String portalApiUrl, String reviewAppsAuthKey) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI(portalApiUrl + CHECK_ORG_ATT_EXP))
.setHeader(AUTH_REVIEW_API_KEY, reviewAppsAuthKey)
.setHeader(CONTENT_TYPE, APPLICATION_JSON)
.GET()
.build();
HttpClient httpClient = HttpClient.newHttpClient();
HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == HttpStatus.OK.value()) {
LOGGER.info(API_SUCCESS);
return API_SUCCESS;
}
} catch (URISyntaxException e) {
LOGGER.error(API_FAIL_URI, e.getMessage());
} catch (InterruptedException e) {
LOGGER.error(API_FAIL_INTER, e.getMessage());
} catch (IOException e) {
LOGGER.error(API_FAIL_IO, e.getMessage());
}
return API_FAILURE;
}
}
Junit :
@Test
public void sendAPICallTest() throws IOException, InterruptedException {
Checkorg test = getCheckOrg();
String portalApiUrl = JUNIT_PORTAL_URL;
String reviewAppsAuthKey = JUNIT_AUTH_KEY;
String message = test.sendAPICall(portalApiUrl, reviewAppsAuthKey);
assertEquals(Checkorg.API_SUCCESS, message);
}
How to mock the HTTP Client in Test Class.
Thank you
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据您的评论:
您可以使用
间谍
为此:如果httpclient模拟不可行,这可能是一个快速的解决方法。
As per your comment:
you can use
spy
for that :This can be a quick workaround if HttpClient mocking is not feasible.