1.doThrow 适用于 没有出参的方法
@GetMapping(value = "/findUserMenuItems")
@ApiOperation(value = "查询用户菜单", notes = "查询用户菜单")
public List<MenuItemVO> findUserMenuItems(@RequestParam(value = "userId") Long userId,
@RequestParam(value = "orgId") Long orgId) {
return menuItemManager.findUserMenuItems(userId, orgId);
}
模拟抛异常的场景:
@Test(expected = RuntimeException.class)
public void 查询用户菜单_失败_抛异常() {
//given
Long userId = anyLong();;
Long orgId = anyLong();
when(menuItemManager.findUserMenuItems(anyLong(), anyLong())).thenThrow(new RuntimeException());
//when
apiMenuItemController.findUserMenuItems(userId, orgId);
//then
}
2.thenThrow 适用于 有出参的方法
@PostMapping(value = "/createMenuItem")
@ApiOperation(value = "创建菜单", notes = "创建菜单")
public void createMenuItem(@RequestBody CreateMenuItemDTO createMenuItemDTO) {
menuItemManager.createMenuItem(createMenuItemDTO);
}
模拟抛异常的场景:
@Test(expected = RuntimeException.class)
public void 创建菜单_失败_抛异常() {
//given
CreateMenuItemDTO createMenuItem = new CreateMenuItemDTO();
doThrow(new RuntimeException()).when(menuItemManager).createMenuItem(createMenuItem);
//when
apiMenuItemController.createMenuItem(createMenuItem);
//then
}
3.注意抛异常的语句是when
如下:
//given
doThrow(new RuntimeException()).when(menuItemManager).createMenuItem(createMenuItem);
//when
apiMenuItemController.createMenuItem(createMenuItem);
假如放在调用方法之后是不严谨的,并且是不规范的,还需要再增加一条语句,如下:
//when
apiMenuItemController.createMenuItem(createMenuItem);
doThrow(new RuntimeException()).when(menuItemManager).createMenuItem(createMenuItem);
menuItemManager.createMenuItem(createMenuItem);