验证是否调用了list元素方法

时间:2016-11-24 04:36:24

标签: java unit-testing junit mockito

如何验证在单元测试期间是否调用了list元素的方法签名?对于下面的代码段,如何验证在使用item.getPrice()模拟对象进行验证时是否调用order

实施代码段:

public BigDecimal getTotalPrice(Order order) {
    BigDecimal totalPrice = BigDecimal.ZERO;
    for (Item item : order.getItems()) {
        totalPrice.add(item.getPrice());
    }

    return totalPrice;
}

单元测试代码段:

@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
}

测试总是失败,这里是stacktrace(片段);

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Misplaced argument matcher detected here:

-> // pointing to this line : verify(order.getItems().get(anyInt()), atLeastOnce()).getPrice();

实施此单元测试场景的最佳方法是什么?

1 个答案:

答案 0 :(得分:1)

尝试

//...other code removed for brevity
for (Item item : items) {
    verify(item, atLeastOnce()).getPrice();
}