Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify if list element method is called

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?

like image 509
David B Avatar asked Oct 22 '25 04:10

David B


1 Answers

Try

//...other code removed for brevity
for (Item item : items) {
    verify(item, atLeastOnce()).getPrice();
}
like image 156
Nkosi Avatar answered Oct 23 '25 20:10

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!