Using @Spy and @Autowired together

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

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

提交回复
热议问题