Mockito Flashcards
What is Mockito
Mockito is an open-source framework that allows us to create test doubles (mocks) easily.
Types of Mocks
Stubs – are objects that have predefined return values to the method executions made during the test.
Spies – are objects that are similar to stubs, but they additionally record the stats of how they were executed.
Mocks – are objects that have return values to method executions made during the test and has recorded expectations of these executions. Mocks can throw an exception if they receive a call they don’t expect and are checked during verification to ensure they got all the calls they were expecting.
Mockito Initialization with Junit5
To process Mockito annotations with JUnit 5, we need to use MockitoExtention as follows:
@ExtendWith(MockitoExtension.class)
public class ApplicationTest {
//code
}
Mockito Initialization with JUnit4
@RunWith(MockitoJUnitRunner.class) or @RunWith(MockitoJUnitRunner.class)
Programmatic Initialization
Alternatively, we can programmatically bootstrap mockito using openMocks() method somewhere in the base class or a test runner.
@BeforeEach
public void setup() { MockitoAnnotations.openMocks(this);
}
Test Class
The class under Test and into which the mocked classes need to be injected. The instance variable is annotated with
@InjectMocks
Mock Class
Your Test Class invokes methods of a Class. You can mock these classes. JUnit will create objects of the Mocked class and inject into your Test Class
The instance variable is annotated with @Mock annotation
Example
To demo the Mockito syntax, we have created a typical usecase where a RecordService invokes RecordDao to save a Record.
@ExtendWith(MockitoExtension.class)
public class MockitoHelloTest {
@Mock
RecordDao mockDao;
@Mock
NotificationService mockNotification;
@Mock
SequenceGenerator mockGenerator;
@InjectMocks
RecordService service;
@Test
public void testSaveRecord() {
Record record = new Record(); record.setName("Test Record"); when(mockGenerator.getNext()).thenReturn(100L); when(mockDao.saveRecord(record)).thenReturn(record); Record savedRecord = service.saveRecord(record); verify(mockGenerator, times(1)).getNext(); verify(mockDao, times(1)).saveRecord(any(Record.class)); assertEquals("Test Record", savedRecord.getName()); assertEquals(100L, savedRecord.getId()); } }
verify
verify() method which is used for verification. By using verify() method you can double check which method of your class is called and how many times. For example, in our case we verified that getNext() of mockGenerator is called once. If its not called once then this test will fail and you will come to know about it