简体   繁体   中英

Mockito Test Case for Custom Exception

I am testing return values in a method but need to also test exceptions. Below is a code snippet of one of the exceptions - how should I test this?

  @Override
    public Response generateResponse(Request request) throws CustomException {           

        try {
            GenerateResponse response = client.generateResponse(headers, generateRequest);
            return response;
        } catch (FeignException.BadRequest badRequest) {
          String message = "Received Bad Request";
            throw new CustomException(message, "" + badRequest.status());
        } catch (FeignException.Unauthorized unauthorized) {
            log.error(unauthorized.contentUTF8());
            String message = "Received UnAuthorized Exception ";
            throw new CustomException(message, "" + unauthorized.status());
        } 
}}

I have tested the happy path for the method I am testing using the following:

Mockito.when(service.getResponse(Mockito.any(), Mockito.any())).thenReturn(getResponse);

Mockito.when(service.getResponse(Mockito.any(), Mockito.any())).thenThrow(new CustomException());

If you want the mock to throw an error, you do not want thenReturn but thenThrow

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