使用 mockito 的 verify() 方法可以验证方法是否被调用过。只需在测试类上添加 @mock 注解创建模拟对象,执行被测代码后,调用 verify(mock).method() 即可确认调用行为。

如何验证方法只被调用了一次?
默认情况下 verify() 检查方法至少被调用一次。若需严格验证仅调用一次,可传入 times(1) 参数。这能防止因多余调用导致的逻辑错误未被发现。

import static org.mockito.Mockito.*;
public class OrderServiceTest {
@Mock
private PaymentGateway gateway;
@Test
public void testPaymentCalledOnce() {
OrderService service = new OrderService(gateway);
service.processOrder("ORD-001", 100.0);
verify(gateway, times(1)).charge(100.0); // 验证恰好调用一次
}
}
如何验证方法从未被调用?
当某些条件不满足时,预期特定方法不应被执行。此时使用 verifyZeroInteractions() 或 verify(mock, never()) 进行断言。这有助于确保业务逻辑中的分支路径正确执行。

import static org.mockito.Mockito.*;
public class DiscountServiceTest {
@Mock
private NotificationService notifier;
@Test
public void testNoNotificationForFreeItem() {
DiscountService service = new DiscountService(notifier);
service.applyDiscount(null); // 免费商品不触发通知
verifyZeroInteractions(notifier); // 验证无任何交互
}
}
基于输入参数为null时的具体验证问题
当传入 null 作为参数时,需验证方法是否按预期处理空值。例如在订单服务中,若订单ID为空,应跳过支付网关调用。通过 verify(gateway, never()).charge(anyDouble()) 可确认未发生任何支付尝试。











