Skip to content

Commit 33fe8d2

Browse files
committed
Document potential need to use Mockito.doXxx() to stub a @⁠MockitoSpyBean
Closes gh-35410
1 parent b741632 commit 33fe8d2

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

framework-docs/modules/ROOT/pages/testing/annotations/integration-spring/annotation-mockitobean.adoc

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,17 @@ exactly one candidate bean exists.
7777

7878
[TIP]
7979
====
80+
As stated in the documentation for Mockito, there are times when using `Mockito.when()` is
81+
inappropriate for stubbing a spy – for example, if calling a real method on a spy results
82+
in undesired side effects.
83+
84+
To avoid such undesired side effects, consider using
85+
`Mockito.doReturn(...).when(spy)...`, `Mockito.doThrow(...).when(spy)...`,
86+
`Mockito.doNothing().when(spy)...`, and similar methods.
87+
====
88+
89+
[NOTE]
90+
====
8091
Only _singleton_ beans can be overridden. Any attempt to override a non-singleton bean
8192
will result in an exception.
8293

spring-test/src/main/java/org/springframework/test/context/bean/override/mockito/MockitoSpyBean.java

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,15 @@
6767
* {@link org.springframework.beans.factory.config.ConfigurableListableBeanFactory#registerResolvableDependency(Class, Object)
6868
* registered directly} as resolvable dependencies.
6969
*
70+
* <p><strong>NOTE</strong>: As stated in the documentation for Mockito, there are
71+
* times when using {@code Mockito.when()} is inappropriate for stubbing a spy
72+
* &mdash; for example, if calling a real method on a spy results in undesired
73+
* side effects. To avoid such undesired side effects, consider using
74+
* {@link org.mockito.Mockito#doReturn(Object) Mockito.doReturn(...).when(spy)...},
75+
* {@link org.mockito.Mockito#doThrow(Class) Mockito.doThrow(...).when(spy)...},
76+
* {@link org.mockito.Mockito#doNothing() Mockito.doNothing().when(spy)...}, and
77+
* similar methods.
78+
*
7079
* <p><strong>WARNING</strong>: Using {@code @MockitoSpyBean} in conjunction with
7180
* {@code @ContextHierarchy} can lead to undesirable results since each
7281
* {@code @MockitoSpyBean} will be applied to all context hierarchy levels by default.

0 commit comments

Comments
 (0)