When there are 2 beans and one marked as @Primary, in normal auto-wiring, the Primary bean is used. However, in case of test code autowired via @SpyBean, this is not necessary the case. This cause unexpected behavior when using the spybean to mock responses on methods.
I have created a sample project which illustrate this. See the test class and the same code
Looking more into the details. It appear which bean is spied on depends on the order the beans are returned from the method getExistingBeans in MockitoPostProcessor (the last bean return ends up being the one is spied on, since the loop in registerSpies essential overwrite previous spy registered). I would expect we always spy on the bean marked with @Primary similar to the normal auto-wiring behavior.
When there are 2 beans and one marked as
@Primary, in normal auto-wiring, the Primary bean is used. However, in case of test code autowired via@SpyBean, this is not necessary the case. This cause unexpected behavior when using the spybean to mock responses on methods.I have created a sample project which illustrate this. See the test class and the same code
Looking more into the details. It appear which bean is spied on depends on the order the beans are returned from the method
getExistingBeansin MockitoPostProcessor (the last bean return ends up being the one is spied on, since the loop inregisterSpiesessential overwrite previous spy registered). I would expect we always spy on the bean marked with@Primarysimilar to the normal auto-wiring behavior.