遇到mock打樁不生效的問題
------------------我是分割線-----------------------
更新
向大佬請教了一下,本質的原因如下
1. mock的目的是為了排除外部依賴,你只管傳過來一個該方法需要的參數類型,就可以。
2. 我在mock里寫的Path.of,debug的時候跟蹤內存地址發(fā)現(xiàn),在業(yè)務代碼里并不是這個對象,所以打樁無效;而你用any在外面包裹著,只要是這個類型,我就按照打樁的結果去處理。
上代碼
業(yè)務代碼
try {
String path = StringUtils.joinWith("/", reportFile.getFilePath(), reportFile.getFileName());
log.info("------------get into minIO to upload file-------------");
minioService.upload(Path.of(path), file.getInputStream());
//想要在這里mock一下,走到這里的時候拋異常,被捕獲到以后拋出400錯誤
log.info("------------upload file success-------------");
} catch (MinioException | IOException e) {
e.printStackTrace();
throw new BadRequestException("attachment file upload fail");
}
單元測試代碼
doThrow(MinioException.class).when(minioService).upload(Path.of(anyString), any(InputStream.class));
Assertions.assertThrows(BadRequestException.class, () -> attachmentService.addAttachment(HOSP_CODE, REPORT_ID, attachmentDto, multipartFile));
此時不管怎么寫,都是這個錯誤
文章來源:http://www.zghlxwxcb.cn/news/detail-505293.html
原因:mock打樁的時候參數不正確,這個時候不管你怎么寫,這個樁點都不會出發(fā)
正確的寫法:
// 注意看這里,原來是Path.of(anyString())
doThrow(MinioException.class).when(minioService).upload(any(Path.class), any(InputStream.class));
Assertions.assertThrows(BadRequestException.class, () -> attachmentService.addAttachment(HOSP_CODE, REPORT_ID, attachmentDto, multipartFile));
總結
參數不對,努力白費。文章來源地址http://www.zghlxwxcb.cn/news/detail-505293.html
到了這里,關于mock打樁不生效的問題的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!