javaintermediate

Mockito — Mocking and Verification

Mock dependencies with Mockito: when/thenReturn, verify, argument captors, and spy patterns.

java
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.*;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;
import java.util.Optional;

@ExtendWith(MockitoExtension.class)
class OrderServiceTest {

    @Mock UserRepository userRepo;
    @Mock PaymentGateway paymentGateway;
    @Mock EmailService emailService;

    @InjectMocks OrderService orderService;

    @Captor ArgumentCaptor<String> emailCaptor;

    @Test
    void shouldPlaceOrder() {
        // Given
        var user = new User(1L, "Alice", "alice@test.com");
        when(userRepo.findById(1L)).thenReturn(Optional.of(user));
        when(paymentGateway.charge(anyDouble())).thenReturn(true);

        // When
        Order order = orderService.placeOrder(1L, 99.99);

        // Then
        assertNotNull(order);
        assertEquals("CONFIRMED", order.status());

        // Verify interactions
        verify(userRepo).findById(1L);
        verify(paymentGateway).charge(99.99);
        verify(emailService).sendConfirmation(emailCaptor.capture(), any());
        assertEquals("alice@test.com", emailCaptor.getValue());

        // Never called with wrong args
        verify(paymentGateway, never()).refund(anyDouble());
    }

    @Test
    void shouldThrowWhenUserNotFound() {
        when(userRepo.findById(999L)).thenReturn(Optional.empty());

        assertThrows(ResourceNotFoundException.class,
            () -> orderService.placeOrder(999L, 50.0));

        verifyNoInteractions(paymentGateway, emailService);
    }

    @Test
    void shouldRetryPayment() {
        var user = new User(1L, "Bob", "bob@test.com");
        when(userRepo.findById(1L)).thenReturn(Optional.of(user));
        when(paymentGateway.charge(anyDouble()))
            .thenThrow(new RuntimeException("Timeout"))
            .thenReturn(true); // succeeds on retry

        Order order = orderService.placeOrder(1L, 50.0);
        assertEquals("CONFIRMED", order.status());
        verify(paymentGateway, times(2)).charge(50.0);
    }
}

Use Cases

  • Testing service layers with mocked dependencies
  • Verifying method calls and argument values
  • Testing retry and error handling logic

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.