前言:进行单元测试时,有时候无法编写合适的测试用例来满足流程中的异常捕获和catch内的后续操作,此时mock模拟就有大作用了
例如:在进行删除操作时,为了防止在删除过程中突发数据库断连等情况,使用了try、catch进行异常的捕获和输出,但是在单元测试中编写测试实例时不可能实现这一种操作,所以就需要使用mock来模拟抛出异常
try {
Boolean entity = targetMapper.deleteComment(id);
if (entity) {
return RestResponse.ok().message("删除成功");
}
return RestResponse.failed().message("删除失败");
} catch (Exception e) {
return RestResponse.failed().message("删除失败,出现异常");
}
实现代码如下,慢慢解释
@Test
public void testDeleteExceptionTest() throws Exception{
//删除失败,出现异常
//输入数据
CareCourseComment careCourseComment = new CareCourseComment();
careCourseComment.setId((long)106172);
//预期结果
RestResponse<CareCourseComment> careCourseCommentRestResponse = RestResponse.failed().message("删除失败,出现