Using @Spy and @Autowired together

前端 未结 3 1120
时光取名叫无心
时光取名叫无心 2021-02-04 04:49

I have a Service Class with 3 methods, Service class is also using some @Autowired annotations. Out of 3 methods, I want to mock two methods but use real method for 3rd one.

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-04 05:49

    I was surprised myself but it does work for us. We have plenty places like:

    @Spy
    @Autowired
    private FeatureService featureService;
    

    I think I know why you are facing this problem. It's not about injection, it's about when(bloMock.doSomeStuff()).thenReturn(1) vs doReturn(1).when(bloMock).doSomeStuff(). See: http://www.stevenschwenke.de/spyingWithMockito

    The very important difference is that the first option will actually call the doSomeStuff()- method while the second will not. Both will cause doSomeStuff() to return the desired 1.

提交回复
热议问题