Overview
@MockitoBean
, @MockitoSpyBean
, and @TestBean
currently do not work with @DirtiesContext
modes DirtiesContext.ClassMode.BEFORE_EACH_TEST_METHOD
and MethodMode.BEFORE_METHOD
.
Attempting to use one of those "before method" modes will result in a corresponding @MockitoBean
, @MockitoSpyBean
, or @TestBean
field containing a bean instance from a closed ApplicationContext
. In addition, any other beans in the current, live ApplicationContext
will reference different instances of those @MockitoBean
, @MockitoSpyBean
, and @TestBean
beans.
The reason is that the BeanOverrideTestExecutionListener
is currently assigned an order of LOWEST_PRECEDENCE - 50
; whereas, in order for things to work properly, it must be assigned an order greater than the DirtiesContextBeforeModesTestExecutionListener
and less than the DependencyInjectionTestExecutionListener
.
Related Issues
- https://github.com/spring-projects/spring-boot/issues/11903