Following tutorials show how to use Mockito. (inside JUnit Tests)
Mockito is used to Mock Dependencies (Classes and Methods that are called by the Method being tested)
● first you Mock Class (you need to Mock Class in order to be able to Mock its Methods)
● then you Mock Methods (of Mocked Class)
To Mock Method means to specify return value for specific Input Parameters.
To Mock Method first you need to Mock Class to which this Method belongs to.
Class can be Mocked using either @Mock or @Spy.
In both cases Mocked Method returns what is defined by Mockito and not what the actual implementation would return.
Mock Object
@Mock PersonRepository personRepositoryMock;
@Spy PersonRepository personRepositoryMock;
Inject Mocked Objects (in place of @Autowired)
@InjectMocks MyController myController;
Mock Method
when (personRepositoryMock.getPersonById(1)).thenReturn(new Person(1, "Susan", 50));
given(personRepositoryMock.getPersonById(1)).willReturn(new Person(1, "Susan", 50)); /Alias for when()
doReturn(new Person(1, "Susan", 50)).when(personRepositoryMock).getPersonById(1); //Alternative for when()
The difference is that with
● @Mock Real Method is never called
● @Spy Real Method is always called & executed but return value is intercepted & Mocked Value is returned instead
We could say that
● @Mock creates fully Mocked Object (Object only has Mocked Methods defined by Mockito)
● @Spy creates partially Mocked Object (Object has combination of Real and Mocked Methods)
The other subtle difference is that with @Spy Real Methods are always called - calls to Real Methods are not blocked.
● If Method was Mocked it will return what was defined by Mockito after it gets executed.
● If Method was not Mocked it will return what was defined by its actual implementation.
Syntax
//MOCK DEPENDENCY CLASS (choose @Mock or @Spy)
@Mock PersonRepository personRepositoryMock;
@Spy PersonRepository personRepositorySpy;
//INJECT MOCKS (into Class being tested where @autowired is used)
@InjectMocks MyController myController;
//MOCK METHOD OF DEPENDENCY CLASS (Methods are mocked in the same way for both @Mock and @Spy)
when(personRepositoryMock.getPersonById(1)).thenReturn(new Person(1, "Susan", 50));
when(personRepositorySpy .getPersonById(1)).thenReturn(new Person(1, "Susan", 50));