自定义异常的Mockito测试用例

vql8enpb  于 2023-01-26  发布在  其他
关注(0)|答案(1)|浏览(217)

我正在测试一个方法中的返回值,但是还需要测试异常。下面是其中一个异常的代码片段-我应该如何测试它?

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

我已经使用以下代码测试了我正在测试的方法的快乐路径:

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

uyto3xhc1#

Mockito.when(service.getResponse(Mockito.any(), Mockito.any())).thenThrow(new CustomException());
如果您希望模拟抛出错误,则不希望使用Return,而希望使用Throw

相关问题