Reputation: 3581
How to verify if list element's method signature/s are invoked during unit test/s? For the code snippet below, how to verify if item.getPrice()
was called when verify using order
mock object?
Implementing code snippet:
public BigDecimal getTotalPrice(Order order) {
BigDecimal totalPrice = BigDecimal.ZERO;
for (Item item : order.getItems()) {
totalPrice.add(item.getPrice());
}
return totalPrice;
}
Unit test code snippet:
@Test
public void testTotalPrice() {
List<Item> items = new ArrayList<>();
for (BigDecimal price : prices) {
Item item = mock(Item.class);
when(item.getPrice()).thenReturn(price);
items.add(item);
}
Order order = mock(Order.class);
when(order.getItems()).thenReturn(items)
BigDecimal totalPrice = orderHandler.getTotalPrice(order);
verify(order, atLeastOnce()).getItems();
verify(order.getItems().get(anyInt()), atLeastOnce()).getPrice();
// assert
}
Test always getting failed, here the stacktrace (snippet);
org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:
-> // pointing to this line : verify(order.getItems().get(anyInt()), atLeastOnce()).getPrice();
What's the best way to implement this unit test scenario?
Upvotes: 4
Views: 981
Reputation: 247363
Try
//...other code removed for brevity
for (Item item : items) {
verify(item, atLeastOnce()).getPrice();
}
Upvotes: 3