Skip to content

Identical Bean Overrides are silently allowed #34054

@sbrannen

Description

@sbrannen

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.

@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.

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

Metadata

Metadata

Assignees

Labels

in: testIssues in the test moduletype: bugA general bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions