Reject non-singletons in Test Bean Override support

Prior to this commit, a non-singleton FactoryBean was silently replaced
by a singleton bean. In addition, bean definitions for prototype-scoped
and custom-scoped beans were replaced by singleton bean definitions
that were incapable of creating the desired bean instance. For example,
if the bean type of the original bean definition was a concrete class,
an attempt was made to invoke the default constructor which either
succeeded with undesirable results or failed with an exception if the
bean type did not have a default constructor. If the bean type of the
original bean definition was an interface or a FactoryBean that claimed
to create a bean of a certain interface type, an attempt was made to
instantiate the interface which always failed with a
BeanCreationException.

To address the aforementioned issues, this commit reworks the logic in
BeanOverrideBeanFactoryPostProcessor so that an exception is thrown
whenever an attempt is made to override a non-singleton bean.

Closes gh-33602
This commit is contained in:
Sam Brannen
2024-09-27 17:36:22 +02:00
parent 4e9b503055
commit d79258ac73
10 changed files with 70 additions and 83 deletions

View File

@@ -36,6 +36,9 @@ xref:testing/testcontext-framework/bean-overriding.adoc#testcontext-bean-overrid
and the original instance is wrapped in a Mockito spy. This strategy requires that
exactly one candidate bean definition exists.
NOTE: Only _singleton_ beans can be overridden. Any attempt to override a non-singleton
bean will result in an exception.
The following example shows how to use the default behavior of the `@MockitoBean` annotation:
[tabs]

View File

@@ -87,3 +87,6 @@ Alternatively, a factory method in an external class can be referenced via its
fully-qualified method name following the syntax `<fully-qualified class name>#<method name>`
for example, `methodName = "org.example.TestUtils#createCustomService"`.
====
NOTE: Only _singleton_ beans can be overridden. Any attempt to override a non-singleton
bean will result in an exception.

View File

@@ -69,3 +69,6 @@ Alternatively, the user can directly provide the bean name in the custom annotat
Some `BeanOverrideProcessor` implementations could also internally compute a bean name
based on a convention or another advanced method.
====
NOTE: Only _singleton_ beans can be overridden. Any attempt to override a non-singleton
bean will result in an exception.