@SpyBean
之间有什么区别?来自 org.springframework.boot.test.mock.mockito.SpyBean
和 @Spy
来自 org.mockito.Spy
?
使用 @SpyBean
而不是 @Spy
让我的tests失败。
最佳答案
@Spy
doc说:
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说:
Annotation that can be used to apply Mockito spies to a Spring ApplicationContext.
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
只能创建空构造函数的对象。
关于java - Spring(@SpyBean)与 Mockito(@Spy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54709589/