What is the difference between @SpyBean
from org.springframework.boot.test.mock.mockito.SpyBean
and @Spy
from org.mockito.Spy
?
Using @SpyBean
instead of @Spy
makes my tests fail.
2. The @MockBean annotation is used to apply Mockito mocks whereas @SpyBean annotation is used to apply Mockito spies. 3. When we mock an object of a class, we get an empty object and not the actual object.
Annotation Type SpyBean. Annotation that can be used to apply Mockito spies to a Spring ApplicationContext . Can be used as a class level annotation or on fields in either @Configuration classes, or test classes that are @RunWith the SpringRunner . Spies can be applied by type or by bean name .
@Mock is used when the application context is not up and you need to Mock a service/Bean. @MockBean is used when the application context(in terms of testing) is up and you need to mock a service/Bean.
In Mockito, spy() method is used for creating spy objects. It allows us to call the normal methods of the real object.
@Spy
doc says:
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 says:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With