我有一个带有 3 个方法的服务类,服务类还使用一些 @Autowired 注释。
在 3 种方法中,我想模拟两种方法,但对第三种方法使用真实方法。
问题是:
- 如果我将 @Autowired 与 @Spy 一起使用,则将调用所有三个实际方法实现。
- 如果我仅使用@Spy,则对实际方法的调用将返回空指针,因为没有自动连线对象的初始化。
我知道这两个选项:
- Use @SpyBean https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/test/mock/mockito/SpyBean.htmlspring-boot-test 的注释作为唯一的注释
@Autowired
@InjectMocks
private ProductController productController;
@SpyBean
private ProductService productServiceSpy;
- 使用 Java 反射来“自动装配”间谍对象,例如反射测试工具 https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/test/util/ReflectionTestUtils.html
@Autowired
private ProductController productController;
@Autowired
private ProductService productService;
@Before
public void setUp() {
ProductService productServiceSpy = Mockito.spy(productService);
ReflectionTestUtils.setField(productController, "productService", productServiceSpy);
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)