Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring (@SpyBean) vs Mockito(@Spy)

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.

like image 402
LiTTle Avatar asked Feb 15 '19 12:02

LiTTle


People also ask

What is the difference between SpyBean and MockBean?

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.

What is SpyBean annotation?

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 .

What is the difference between @mock and @MockBean?

@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.

What is Mockito spy used for?

In Mockito, spy() method is used for creating spy objects. It allows us to call the normal methods of the real object.


1 Answers

@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.

like image 91
csenga Avatar answered Sep 20 '22 11:09

csenga