java - Mockito 嘲笑 void 方法
问题描述
我正在使用 Mokito 进行测试,我有以下场景。我正在尝试测试此代码
public CartResponse processDeleteCartEntry(UUID cartId, Integer rowKey, JsonMessages messages)
throws UnexpectedException {
Cart cart = cartService.getById(cartId);
CartResponse cartResponse = null;
if (cart != null) {
cartService.removeItem(cart, rowKey, messages);
cartResponse = buildCartResponse(cart);
}
return cartResponse;
}
cartService.removeItem(cart, rowKey, messages);
不返回任何东西(无效),这是我的测试用例
@Test
public void testRemoveCartItem() throws UnexpectedException {
Cart cart = getCart();
//given
given(cartService.getById(cart.getId())).willReturn(cart);
//When
CartResponse cartResponse = mobileAppCartHandler.processDeleteCartEntry(cart.getId(), 0, new JsonMessages());
//Then
assertNotNull(cartResponse);
assertEquals(ResponseStatus.OK, cartResponse.getStatus());
assertEquals(1, cartResponse.getEntries().size());
}
我不想进行实际调用来删除一个项目,但同时它应该删除该项目以便我可以断言它。我的购物车有 2 件物品,移除后应该是一件。我应该使用when
条件吗?
解决方案
对于 void 方法,您需要先存根操作。
Mockito.doAnswer(invocation -> {
// grab args and remove from cart
})
.when(cartService) // mocked cartService
.removeItem(cart, rowKey, messages); // You can use argumentMatchers here
推荐阅读
- c# - 基于分组c#的WCF服务响应设计
- excel - 根据空单元格位置设置变量偏移
- delphi - 在运行时更新更多图像时的Delphi XE(Firemonkey)问题(android)
- html - 仅使用 CSS 的父 div 的动态大小动画
- python - ValueError:endog 和 exog 矩阵的大小不同 - 如何仅删除特定列中的数据?
- javascript - WebSocket“消息”,流中只有一个结果
- c - 用C将数字序列写入文件
- android - 在 Android 中为每个用户显示来自 Firebase 的课程数据
- android - 身份验证失败:invalid_clientUnauthorized
- node.js - 将 keycloak.protect() 与 express.Router() 一起使用