verify() is Mockito's mechanism for behavior verification - confirming that specific methods were called on a mock, how many times, and with what arguments.
Key Points: • Basic usage: verify(mock).someMethod(args) checks the call happened exactly once with those arguments. • Call count can be tightened with verify(mock, times(n)), never(), atLeastOnce(), or atMost(n). • ArgumentMatchers like any() or eq() can loosen or refine which arguments are expected. • verifyNoInteractions() and verifyNoMoreInteractions() confirm a mock was never touched, or that nothing beyond what you verified occurred. • Verification order across multiple mocks can be checked using InOrder.
Example: For a NotificationService that should email a user exactly once after checkout, you'd write verify(mailSender, times(1)).send(eq("user@example.com"), any(String.class)).
Code Example:
@Test
void sendsWelcomeEmailOnce() {
MailSender mailSender = mock(MailSender.class);
UserService service = new UserService(mailSender);
service.register("user@example.com");
verify(mailSender, times(1)).send(eq("user@example.com"), anyString());
}Interview Tip: A concise interview answer is:
"I use verify() to assert that a mock was interacted with the way I expect - a specific method, call count, and arguments - using helpers like times(), never(), and argument matchers. It's how I confirm side-effecting behavior, like sending an email, actually happened without a return value to check."