Mockito 模拟 void 方法

Mockito mocking the void methods

我正在使用 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); 没有 return 任何东西 (void) 这是我的测试用例

@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 函数使用 doAnswer

@Test
public void testRemoveCartItem() throws UnexpectedException {
    Cart cart = getCart();
    int rowKey = 0;
    JsonMessages messages = new JsonMessages()();

    //given
    given(cartService.getById(cart.getId())).willReturn(cart);

    doAnswer(new Answer<Void>() {
        @Override
        public void answer(InvocationOnMock invocation) throws Throwable {
            //get the arguments passed to mock
            Object[] args = invocation.getArguments();

            //get the mock 
            Object mock = invocation.getMock(); 

            Cart c = (Cart)args[0];
            int row = (int)(Integer)args[1];

            c.removeItem(row); //Just an assumption here

            //return
            return null;
        }
    })
    .when(cartService).removeItem(cart, rowKey, messages);

    //When
    CartResponse cartResponse = mobileAppCartHandler.processDeleteCartEntry(cart.getId(), rowKey, messages);

    //Then
    assertNotNull(cartResponse);
    assertEquals(ResponseStatus.OK, cartResponse.getStatus());
    assertEquals(1, cartResponse.getEntries().size());

}

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

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