Mocking Dependencies

Why Mocking Dependencies Matters

Spring Boot @MockBean replaces real beans with Mockito mocks in test ApplicationContext. In integration tests requiring external API mocking (payment gateways, email services), @MockBean eliminates TestConfiguration boilerplate—injecting mocks into Spring context while maintaining autowiring and dependency injection for focused testing.

Problem: Manual Mockito setup requires explicit mock creation and Spring context configuration.

Solution: @MockBean annotation replaces beans in test ApplicationContext.

Implementation Example

@SpringBootTest
class DonationServiceTest {

    @Autowired
    private DonationService donationService;

    @MockBean  // => Replaces real ReceiptService with Mockito mock
    private ReceiptService receiptService;

    @Test
    void shouldProcessDonation() {
        // => Configure mock behavior
        when(receiptService.generateReceipt(any()))
            .thenReturn(new Receipt("RCP-001"));

        DonationResponse response = donationService.processDonation(request);

        // => Verify mock interaction
        verify(receiptService).generateReceipt(any());
        assertThat(response.getReceiptNumber()).isEqualTo("RCP-001");
    }
}

Production Configuration

# Configuration for mocking-dependencies
# See full guide for detailed configuration

Production Patterns

Best Practices:

  • Follow Spring Boot conventions
  • Test in staging before production
  • Monitor metrics and health checks
  • Use environment-specific configuration

Trade-offs

AspectSpring Boot ApproachManual Approach
ComplexityAuto-configured (simple)Manual configuration (complex)
FlexibilityConventions with overridesFull control
MaintenanceFramework-maintainedCustom code maintenance
Production readyDefaults optimizedRequires tuning

Production recommendation: Use Spring Boot auto-configuration as default. Manual configuration only for edge cases.

Next Steps

  • See related in-the-field guides for comprehensive production patterns
Last updated