Using @Spy and @Autowired together

前端 未结 3 1157
时光取名叫无心
时光取名叫无心 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:24

    Using @Spy together with @Autowired works until you want to verify interaction between that spy and a different component that spy is injected into. What I found to work for me was the following approach found at https://dzone.com/articles/how-to-mock-spring-bean-version-2

    @Configuration
    public class AddressServiceTestConfiguration {
        @Bean
        @Primary
        public AddressService addressServiceSpy(AddressService addressService) {
            return Mockito.spy(addressService);
        }
    }
    

    This turns your autowired component into a spy object, which will be used by your service and can be verified in your tests.

提交回复
热议问题