簡體   English   中英

Mockito mocking 作廢方法

[英]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); 不返回任何東西(無效) ,這是我的測試用例

@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

對於無效 function 使用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());

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM