UPDATE 20220509-203459
For TestNg User,
Add this to the test class
@TestExecutionListeners(listeners = MockitoTestExecutionListener.class)
and extends AbstractTransactionalTestNGSpringContextTests
then @SpyBean will work.
Two choices are given in this Answer
Howerver, I met problems.
- Use @SpyBean annotation from spring-boot-test as the only annotation
This seems a good idea but only for junit users. I am using TestNg in my tests.
I have not found a way to make @SpyBean work well with TestNg.
- Use Java reflection to "autowire" the spy object, e.g. ReflectionTestUtils
The beans autowired seem all have final methods, because spring have already proxy them and make methods final. So Mockito.spy a autowired bean maybe impossible.
Indeed, i tried and got a exception:
invalid use of argument matchers 0 matchers expected 1 recorded
I didnot find reason myself but i saw explanation from here
So, the only approach left is https://stackoverflow.com/a/55148514/12133207
I am not sure if it does work, I will try.
-- tried,not work. maybe because the method parameter is also spring proxied. The methods are alse final.