简体   繁体   中英

How to throw and mock exception in mockito and Junit5. And how to write test case for that

When the URL is wrong or something wrong with the response during third party API call in getMethodWithHeader this method will throw HttpClientErrorException so how to write a test case for this

This is my main code method

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

I want to throw HttpClientErrorException and test it

This is the test code

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

You are almost there:

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

you can turn that into

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

and have that throw whatever you want.

Of course, you also want to adapt the assertions accordingly, for example to check for that 404 status and "Not Found" message.

But note, the real answer here is: read the documentation, and do your own research.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM