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
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());
}
添加回答
举报