When creating tests and mocking dependencies, what is the difference between these three approaches?
@MockBean:
@MockBean MyService myservice;@Mock:
@Mock MyService myservice;Mockito.mock()
MyService myservice = Mockito.mock(MyService.class);
When creating tests and mocking dependencies, what is the difference between these three approaches?
@MockBean:
@MockBean
MyService myservice;
@Mock:
@Mock
MyService myservice;
Mockito.mock()
MyService myservice = Mockito.mock(MyService.class);
Mocktio.mock() :-
when(..) and thenReturn(..) methods for mock objects
whose class methods will be invoked during test case execution.@Mock :-
mock() method so it is preferable and often
used.mock() and @Mock are functionally equivalent.To enable the Mockito annotation during test execution we need to call the MockitoAnnotations.initMocks(this) method but this method is deprecated instead we can call - MockitoAnnotations.openMocks(this). In order to avoid the side effects it is advised to call this method before test case executions.
Another way to enable the Mockito annotations is by annotating the test class with @RunWith by specifying the MockitoJUnitRunner that does this task and also other useful things.
@MockBean :-
It is used to add the mock objects into spring application context.
This mock will replace the existing bean of same type in application
context. If no bean is available, then new bean will be added. This
is useful in integration test case.
When we write a test case that doesn't need any dependencies from the Spring Boot container, the classic/plain Mockito is used and it is fast and favors the isolation of the tested component.
If our test case needs to rely on the Spring Boot container and want to add or mock one of the container beans then @MockBean is used.