简体   繁体   中英

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?

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

For void function use 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());

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM