Practice: Mockito

Practice: Mockito#

Question #0: What is the purpose of Mockito?

Question #1: This sentence is about the default values returned by a mocked object. Fill in the blanks.

A mocked method that is not stubbed will return ______ for objects, ______ for primitives, and an ______ collection for lists/maps.

Question #2: Provide the stubbing code in the following:

@Test
void returnsHello() {
    MyRepo repo = mock(MyRepo.class);

    // TODO: stub repo.fetchMessage() to return "Hello"

    assertEquals("Hello", repo.fetchMessage());
}

Question #3: When would a developer use @Mock instead of using the mock() API directly? For example, the code below shows two tests, each creating a mock in a different way. Is one better than the other? Why?

@Mock
public MyDependency dep;

@Test
void test_using_auto_mock() {
    MyTestTarget target = new MyTestTarget(dep);
    boolean actual = target.action();
    assertTrue(actual);
}

@Test
void test_using_manual_mock() {
    MyDependency dep = Mock(MyDependency.class);
    MyTestTarget target = new MyTestTarget(dep);
    boolean actual = target.action();
    assertTrue(actual);
} 

Question #4: Explain the difference between @Mock and @Spy.

Question #5: Provide the missing annotations in the snippet of code. Critically analyze and explain your answer?

@ExtendWith(MockitoExtension.class)
class SnippetA {

    // TODO: Annotation goes here
    MyDependency dep;

    @InjectMocks
    MyService service;

    @Test
    void test_action() {        
        when(dep.actionA("example")).thenReturn(true);

        boolean ok = service.action("example");

        assertTrue(ok);
        verify(dep).actionA("example");
    }
}

Question #6: Explain what the Mockito method verify does?