Spring (@SpyBean) 与 Mockito(@Spy) [英] Spring (@SpyBean) vs Mockito(@Spy)

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

问题描述

org.springframework.boot.test.mock.mockito.SpyBean 中的 @SpyBean@Spy 之间有什么区别?代码>org.mockito.Spy?

What is the difference between @SpyBean from org.springframework.boot.test.mock.mockito.SpyBean and @Spy from org.mockito.Spy?

使用 @SpyBean 而不是 @Spy 使我的 测试失败.

Using @SpyBean instead of @Spy makes my tests fail.

推荐答案

@Spy doc 说:

使用@Spy 注释的字段可以在以下位置显式初始化声明点.或者,如果您不提供实例Mockito 将尝试找到零参数构造函数(甚至是私有的)和为您创建一个实例.

A field annotated with @Spy can be initialized explicitly at declaration point. Alternatively, if you don't provide the instance Mockito will try to find zero argument constructor (even private) and create an instance for you.

@SpyBean doc 说:

可用于将 Mockito 间谍应用到 Spring 的注解应用上下文.

Annotation that can be used to apply Mockito spies to a Spring ApplicationContext.

同一类型上下文中的所有bean都将用间谍.如果没有定义现有 bean,则会添加一个新 bean.

All beans in the context of the same type will be wrapped with the spy. If no existing bean is defined a new one will be added.

所以主要区别在于 @SpyBean 是 Spring Boot 特定的注释,而 @Spy 是 Mockito 本身的一部分.@SpyBean@Spy 基本相同,但 @SpyBean 可以解析 Spring 特定的依赖关系,例如@Autowired, @Spy 只能创建构造函数为空的对象.

So the main difference is @SpyBean is a Spring Boot specific annotation but @Spy is part of Mockito itself. @SpyBean and @Spy basically do the same, but @SpyBean can resolve the Spring specific dependencies, e.g. @Autowired, @Spy can only create object with empty constructor.

这篇关于Spring (@SpyBean) 与 Mockito(@Spy)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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