Overview
While working on #34025, I noticed that the Bean Overrides feature in Spring Framework behaves differently than Spring Boot's @MockBean
/@SpyBean
support with regard to identical overrides.
Specifically, Spring Boot's DefinitionsParser
preemptively rejects "identical" overrides and throws an IllegalStateException
to signal the configuration error to the user.
https://github.com/spring-projects/spring-boot/blob/51c992593fa17804f1432e4da2f939ee48e9b481/spring-boot-project/spring-boot-test/src/main/java/org/springframework/boot/test/mock/mockito/DefinitionsParser.java#L108-L113
Whereas, the Bean Override feature silently allows an identical bean override to override a previous bean override, which can be seen in the following test classes.
https://github.com/spring-projects/spring-framework/blob/2015a93823b98aa8ea0a0460b8b09b580f53ed8c/spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBeanForByNameLookupIntegrationTests.java#L44-L48
Here, the @MockitoSpyBean("field")
declarations on field
and renamed1
are identical and should be rejected. However, the second bean override declared for the renamed1
field actually "overrides the override" for the field
field, resulting in a single spied bean in the ApplicationContext
. Granted, one would logically only expect one such spied bean, but multiple attempts to spy on the same bean should be rejected since there is no reason to "override an override" with a duplicate, identical override.
The scenario in MockitoBeanDuplicateTypeIntegrationTests
is similar, but the outcome is different.
https://github.com/spring-projects/spring-framework/blob/b904753a256d7f67f733808e9f6951f0974a592e/spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanDuplicateTypeIntegrationTests.java#L40-L44
Here, the two effectively identical @MockitoBean
declarations result in two mock beans being created, since the ApplicationContext
does not originally contain any bean of type ExampleService
.
Proposal
To align with the behavior of @MockBean
and @SpyBean
in Spring Boot regarding the rejection of identical overrides, and to help developers avoid scenarios that are potentially confusing or difficult to debug, we should also reject identical bean overrides in the Spring TestContext Framework.
Related Issues
-
34025