Mock里边的doThrow与thenThrow的区别

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);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值