As I returned back to Java programming, I had to revise my concepts of Junit testing and Mockito. The following is a refresher with quick mockito basics for anyone who wishes to go through them.
* Keep in mind the current version is as and when I am learning mockito myself *
At a high level we divide mocking in the following broad steps
Initialization
//Creating a mock Object of the given class
<ClassName> mockObj = Mockito.mock(<ClassName>.class);
//example
OrderDao mockOrderDao = Mockito.mock(OrderDao.class);
@Mock
AddService addService;
@BeforeEach
public void setup() {
//initMocks works with @Mock, @Spy, @Captor, or @InjectMocks annotated objects
//InjectMock inserts mocks in either a Mocked component, or an autowired service or just an instance of a component
//Spy
//Captor
MockitoAnnotations.initMocks(this);
}
@Test
public void testCalc() {
calcService = new CalcService(addService);
int num1 = 11; int num2 = 12; int expected = 23;
when(addService.add(num1, num2)).thenReturn(expected);
int actual = calcService.calc(num1, num2);
assertEquals(expected, actual);
}