首页 > 解决方案 > 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条件吗?

标签: javaspring-mvcmockingmockitointegration-testing

解决方案


对于 void 方法,您需要先存根操作。

Mockito.doAnswer(invocation -> {
  // grab args and remove from cart
})
.when(cartService)  // mocked cartService
.removeItem(cart, rowKey, messages);  // You can use argumentMatchers here

推荐阅读