一起使用@Spy和@Autowired [英] Using @Spy and @Autowired together

查看:189
本文介绍了一起使用@Spy和@Autowired的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有3种方法的服务类,服务类也使用了@Autowired批注.在3种方法中,我想模拟两种方法,但对第三种方法使用真实方法.

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.

问题是:

  1. 如果我将@Autowired与@Spy一起使用,则将调用所有三个实际方法实现.
  2. 如果仅使用@Spy,则由于没有自动装配对象的初始化,因此使用Null指针返回对真实方法的调用.

推荐答案

我知道这两个选项:

  1. 使用 @SpyBean 注释是唯一的注释
  1. Use @SpyBean annotation from spring-boot-test as the only annotation

@Autowired
@InjectMocks
private ProductController productController;

@SpyBean
private ProductService productServiceSpy;

  1. 使用Java反射来自动装配"间谍对象,例如 ReflectionTestUtils

@Autowired
private ProductController productController;

@Autowired
private ProductService productService;

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

这篇关于一起使用@Spy和@Autowired的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆