亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Mockito 嘲笑 void 方法

Mockito 嘲笑 void 方法

鳳凰求蠱 2023-10-12 17:16:30
我正在使用 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);不返回任何內容(無效),這是我的測試用例@Testpublic 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條件嗎?
查看完整描述

2 回答

?
蝴蝶不菲

TA貢獻1810條經驗 獲得超4個贊

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


Mockito.doAnswer(invocation -> {

  // grab args and remove from cart

})

.when(cartService)  // mocked cartService

.removeItem(cart, rowKey, messages);  // You can use argumentMatchers here


查看完整回答
反對 回復 2023-10-12
?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

對于 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());


}


查看完整回答
反對 回復 2023-10-12
  • 2 回答
  • 0 關注
  • 149 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號