You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Dummy objects are passed around but never actually used. Usually, they are just used to fill parameter lists.
Fake objects have working implementations, but usually, take some shortcut that makes them not suitable for production (an in-memory database is a good example).
Stubs provide canned answers to calls made during the test, usually not responding at all to anything outside what’s programmed in for the test. Stubs may also record
information about calls, such as an email gateway stub that remembers the messages it ‘sent’, or maybe only how many messages it ‘sent’.
Mocks are what we are talking about here: objects pre-programmed with expectations that form a specification of the calls they are expected to receive.
Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks
The most widely used annotation in Mockito is @Mock. We can use @Mock to create and inject mocked instances without having to call Mockito.mock manually.
when(mockedList.size()).thenReturn(100); //both can work in mockdoReturn(100).when(spyList).size();
@Spy Annotation
@Spy annotation to spy on an existing instance.
// when(mockedList.size()).thenReturn(100); this is not going to work in Spy objectdoReturn(100).when(spyList).size();
@Captor
make use of @Captor for the same purpose, to create an ArgumentCaptor instance
MyListlistMock = mock(MyList.class);
doAnswer(invocation -> "Always the same").when(listMock).get(anyInt());
Stringelement = listMock.get(1);
assertThat(element).isEqualTo("Always the same");
doAnswer
Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.
When you are using Spy instead of Mock
When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample