Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Mocking for Unit Test using Mockito

Mocking for Unit Test using Mockito

Mocking for Unit Test using Mockito

Eko Kurniawan Khannedy

February 14, 2018
Tweet

More Decks by Eko Kurniawan Khannedy

Other Decks in Technology

Transcript

  1. MOCKING FOR UNIT TEST USING MOCKITO EKO KURNIAWAN KHANNEDY ▸

    Principal R&D Engineer at Blibli.com ▸ Part of R&D Team at Blibli.com ▸ [email protected]
  2. MOCKING FOR UNIT TEST USING MOCKITO AGENDA ▸ Mocking ▸

    Stubbing ▸ Verification ▸ Capturing
  3. MOCKING IS CREATING OBJECTS THAT MIMIC THE BEHAVIOR OF REAL

    OBJECTS What is Mocking? MOCKING FOR UNIT TEST USING MOCKITO
  4. MOCKING FOR UNIT TEST USING MOCKITO MOCKING USING MOCKITO import

    static org.mockito.Mockito.*; HttpServletRequest request = mock(HttpServletRequest.class);
  5. MOCKING FOR UNIT TEST USING MOCKITO MOCKING USING MOCKITO JUNIT

    RULE @Rule
 public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock
 private HttpServletRequest request;
  6. MOCKING FOR UNIT TEST USING MOCKITO INJECTING MOCK WITH MOCKITO

    @Rule
 public MockitoRule mockitoRule = MockitoJUnit.rule(); @Mock
 private HttpServletRequest request; @InjectMocks
 private MyController controller;
  7. MOCKING FOR UNIT TEST USING MOCKITO STUBBING USING MOCKITO when(request.getParameter("name")).thenReturn(...);

    assertEquals(..., request.getParameter("name")); when(request.getParameter("error")).thenThrown(...); request.getParameter("error"); // throw exception when(request.getParameter("return")).thenAnswer(...);
  8. MOCKING FOR UNIT TEST USING MOCKITO STUBING USING MOCKITO verify(request).getParameter("name");

    verify(request, times(2)).getParameter("..."); verifyNoMoreInteractions(request);
  9. MOCKING FOR UNIT TEST USING MOCKITO CAPTURING USING MOCKITO JUNIT

    RULE @Captor
 private ArgumentCaptor<Merchant> merchantCaptor;
  10. MOCKING FOR UNIT TEST USING MOCKITO GET VALUE FROM CAPTOR

    verify(merchantRepository).save(merchantCaptor.capture()); Merchant merchant = merchantCaptor.getValue();
  11. MOCKING FOR UNIT TEST USING MOCKITO REFERENCES ▸ https://github.com/mockito/mockito/wiki ▸

    https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features- testing.html