javaspringtestingautowiredspy

Using @Spy and @Autowired together


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.

Solution

  • 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);
    }