Search code examples
javaspring-mvcmockingmockitointegration-testing

Mockito mocking the void methods


I am using Mokito for testing and I have the following scenario. I am trying to test this code

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); doesn't return anything (void) and this is my test case

@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());

}

I do not want to make an actual call to remove an item but at the same time it should remove the item so that I can assert it. My cart has 2 items and it should be one after the removal. Should I be using when condition?


Solution

  • For void methods, you need to stub the action first.

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