Using @Spy and @Autowired together

久未见 提交于 2021-02-05 22:57:33

问题


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.

Problem is:

  1. If I am using @Autowired with @Spy, all three real method implementation is being called.
  2. If I am using @Spy only, call to real method is return with Null pointer as there is no initialisation of Autowired objects.

回答1:


I know about these two options:

  1. Use @SpyBean annotation from spring-boot-test as the only annotation
@Autowired
@InjectMocks
private ProductController productController;

@SpyBean
private ProductService productServiceSpy;
  1. Use Java reflection to "autowire" the spy object, e.g. ReflectionTestUtils
@Autowired
private ProductController productController;

@Autowired
private ProductService productService;

@Before
public void setUp() {
    ProductService productServiceSpy = Mockito.spy(productService);
    ReflectionTestUtils.setField(productController, "productService", productServiceSpy);
}



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/44455572/using-spy-and-autowired-together

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!