Mockito 嘲笑 void 方法

我正在使用 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条件吗?


凤凰求蛊
浏览 119回答 2
2回答

蝴蝶不菲

对于 void 方法,您需要首先存根操作。Mockito.doAnswer(invocation -> {  // grab args and remove from cart}).when(cartService)  // mocked cartService.removeItem(cart, rowKey, messages);  // You can use argumentMatchers here

慕慕森

对于 void 函数使用doAnswer@Testpublic void testRemoveCartItem() throws UnexpectedException {&nbsp; &nbsp; Cart cart = getCart();&nbsp; &nbsp; int rowKey = 0;&nbsp; &nbsp; JsonMessages messages = new JsonMessages()();&nbsp; &nbsp; //given&nbsp; &nbsp; given(cartService.getById(cart.getId())).willReturn(cart);&nbsp; &nbsp; doAnswer(new Answer<Void>() {&nbsp; &nbsp; &nbsp; &nbsp; @Override&nbsp; &nbsp; &nbsp; &nbsp; public void answer(InvocationOnMock invocation) throws Throwable {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get the arguments passed to mock&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object[] args = invocation.getArguments();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //get the mock&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object mock = invocation.getMock();&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Cart c = (Cart)args[0];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; int row = (int)(Integer)args[1];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; c.removeItem(row); //Just an assumption here&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //return&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; })&nbsp; &nbsp; .when(cartService).removeItem(cart, rowKey, messages);&nbsp; &nbsp; //When&nbsp; &nbsp; CartResponse cartResponse = mobileAppCartHandler.processDeleteCartEntry(cart.getId(), rowKey, messages);&nbsp; &nbsp; //Then&nbsp; &nbsp; assertNotNull(cartResponse);&nbsp; &nbsp; assertEquals(ResponseStatus.OK, cartResponse.getStatus());&nbsp; &nbsp; assertEquals(1, cartResponse.getEntries().size());}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java