-
Notifications
You must be signed in to change notification settings - Fork 38.6k
Description
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.
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.
Lines 44 to 48 in 2015a93
@MockitoSpyBean("field1") | |
ExampleService field; | |
@MockitoSpyBean("field1") | |
ExampleService renamed1; |
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.
Lines 40 to 44 in b904753
@MockitoBean | |
ExampleService service1; | |
@MockitoBean | |
ExampleService service2; |
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.