diff --git a/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-mockitobean.adoc b/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-mockitobean.adoc index 4cc25b1c176..bb00980aa2d 100644 --- a/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-mockitobean.adoc +++ b/framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-mockitobean.adoc @@ -77,6 +77,17 @@ exactly one candidate bean exists. [TIP] ==== +As stated in the documentation for Mockito, there are times when using `Mockito.when()` is +inappropriate for stubbing a spy – for example, if calling a real method on a spy results +in undesired side effects. + +To avoid such undesired side effects, consider using +`Mockito.doReturn(...).when(spy)...`, `Mockito.doThrow(...).when(spy)...`, +`Mockito.doNothing().when(spy)...`, and similar methods. +==== + +[NOTE] +==== Only _singleton_ beans can be overridden. Any attempt to override a non-singleton bean will result in an exception. diff --git a/spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBean.java b/spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBean.java index c926e69595f..6f4e3276afd 100644 --- a/spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBean.java +++ b/spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBean.java @@ -67,6 +67,15 @@ import org.springframework.test.context.bean.override.BeanOverride; * {@link org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerResolvableDependency(Class, Object) * registered directly} as resolvable dependencies. * + *
NOTE: As stated in the documentation for Mockito, there are + * times when using {@code Mockito.when()} is inappropriate for stubbing a spy + * — for example, if calling a real method on a spy results in undesired + * side effects. To avoid such undesired side effects, consider using + * {@link org.mockito.Mockito#doReturn(Object) Mockito.doReturn(...).when(spy)...}, + * {@link org.mockito.Mockito#doThrow(Class) Mockito.doThrow(...).when(spy)...}, + * {@link org.mockito.Mockito#doNothing() Mockito.doNothing().when(spy)...}, and + * similar methods. + * *
WARNING: Using {@code @MockitoSpyBean} in conjunction with * {@code @ContextHierarchy} can lead to undesirable results since each * {@code @MockitoSpyBean} will be applied to all context hierarchy levels by default.