【问题标题】:How to throw and mock exception in mockito and Junit5. And how to write test case for that如何在 mockito 和 Junit5 中抛出和模拟异常。以及如何为此编写测试用例
【发布时间】: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


    【解决方案1】:

    你快到了:

    when(apiUrlUtil.getNextUrl(Mockito.any())).thenReturn("nextUrl");
    

    你可以把它变成

    when(apiUrlUtil.getNextUrl(Mockito.any())).thenThrow( ... )
    

    然后随心所欲地扔。

    当然,您还想相应地调整 断言,例如检查 404 状态和“未找到”消息。

    但请注意,这里真正的答案是:阅读文档,然后进行自己的研究。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2018-12-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多