What is @MockitoSpyBean in Spring
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
- “Spring Framework 6.2 introduced @MockitoSpyBean, 2025”: https://www.baeldung.com/spring-mockitospybean
- “Spy over Mock for partial mocking in integration tests”: https://www.baeldung.com/spring-mockitospybean
- “Legacy @SpyBean deprecated in Spring 6.2”: https://www.baeldung.com/spring-mockitospybean
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
RestTestClient: Spring Framework 7.0's New Tool for REST Integration Testing
Spring Framework 7.0 introduces RestTestClient, a modern tool for simplifying REST integration testing with fluent APIs.
Grouping Tests with @Suite in Swift Testing
Swift Testing’s @Suite organizes tests hierarchically, improving BDD clarity with Gherkin-style labels.
Conditionally Ignore Tests in TestNG
Explore various approaches to ignore a test in TestNG conditionally, improving test suite flexibility and execution time.