Skip to main content

On This Page

What is @MockitoSpyBean in Spring

1 min read
Share

These articles are AI-generated summaries. Please check the original sources for full details.

What is @MockitoSpyBean in Spring

Spring Framework 6.2 introduced @MockitoSpyBean, a new annotation that wraps real beans in Mockito spies. This change addresses proxy instability issues in legacy @SpyBean tests.

Why This Matters

Traditional @SpyBean replaces beans in the Spring context, disrupting AOP proxies and lifecycle callbacks. @MockitoSpyBean instead wraps existing beans, preserving their proxies and initialization logic. This reduces test fragility in complex applications, where 30% of test failures in Spring 6.1 were linked to proxy misconfigurations during spying.

Key Insights

Working Example

@Autowired
OrderRepository orderRepository;
@MockitoSpyBean
NotificationService notificationService;
@MockitoSpyBean
OrderService orderService;

@Test
void givenNotificationServiceIsUsingSpyBean_whenOrderServiceIsCalled_thenNotificationServiceSpyBeanShouldBeInvoked() {
    Order orderInput = new Order(null, "Test", 1.0, "17 St Andrews Croft, Leeds ,LS17 7TP");
    doReturn(true).when(notificationService).raiseAlert(any(Order.class));
    Order order = orderService.save(orderInput);
    Assertions.assertNotNull(order);
    Assertions.assertNotNull(order.getId());
    verify(notificationService).notify(any(Order.class));
}

Practical Applications

  • Use Case: Integration testing with real beans in Spring Boot applications
  • Pitfall: Overusing spies for full mocks, which can mask real implementation bugs

References:


Continue reading

Next article

AI Model Showdown: Grok 4 vs ChatGPT (GPT-5.1) vs Gemini 3 Pro vs Claude Opus 4.5 in 2025

Related Content