【发布时间】:2022-01-23 15:03:33
【问题描述】:
当在getMethodWithHeader中调用第三方API时URL错误或响应有问题时,该方法将抛出HttpClientErrorException,那么如何为此编写测试用例
这是我的主要代码方法
public JSONObject callRespectiveAPI(String url, String apiKeyAndPassword) {
JSONObject result = new JSONObject();
try {
String accessToken = apiUrlUtil.getAccessToken(apiKeyAndPassword);
ResponseEntity<String> response = apiUrlUtil.getMethodWithHeader(url, accessToken);
String nextUrl = apiUrlUtil.getNextUrl(response.getHeaders());
result = JSONObject.fromObject(response.getBody());
result.put("nextUrl", nextUrl);
} catch(HttpClientErrorException e) {
result.put("status", "404");
result.put("message", "Not Found");
LOGGER.error(e.getMessage());
}
return result;
}
我想抛出 HttpClientErrorException 并测试一下
这是测试代码
@Test
public void callRespectiveAPITest2() {
JSONObject object = new JSONObject();
object.put("success", true);
ResponseEntity<String> response = new ResponseEntity<String>(object.toString(), HttpStatus.OK);
when(apiUrlUtil.getAccessToken(Mockito.anyString())).thenReturn("accessToken");
when(apiUrlUtil.getMethodWithHeader(Mockito.anyString(), Mockito.anyString())).thenReturn(response);
when(apiUrlUtil.getNextUrl(Mockito.any())).thenReturn("nextUrl");
assertEquals(true, shopifyService.callRespectiveAPI("nextUrl", "accessToken").get("success"));
}
【问题讨论】:
标签: java spring-boot unit-testing mockito junit5