Mockito

What is a mock

When a component depends on another, a question arises. Should we test the component with its dependency, or without it? If we want to test the component in isolation, we can replace the dependency with a mock. In the test case, we define a behavior for the mock, then check whether the mock was called as it should have been.

Mockito

Mockito is a mocking framework.

Here is an example of behavior registration:

 1import org.junit.jupiter.api.Test;
 2
 3import java.time.LocalDateTime;
 4import java.time.Month;
 5
 6import static org.junit.jupiter.api.Assertions.*;
 7import static org.mockito.Mockito.*;
 8
 9class EventFactoryTest {
10
11    @Test
12    void shouldCreateEvent() {
13        // Arrange
14        Clock clock = mock(Clock.class);
15        when(clock.getTime())
16                .thenReturn(LocalDateTime.of(2025, Month.SEPTEMBER, 27, 14, 0, 0, 0));
17        EventFactory factory = new EventFactory(clock);
18
19        // Act
20        Event event = factory.create("Charged");
21
22        // Assert
23        assertEquals("Charged", event.getType());
24    }
25
26}

Here is an example of verification:

 1import org.junit.jupiter.api.Test;
 2
 3import static org.mockito.Mockito.*;
 4
 5class AccountsTest {
 6
 7    @Test
 8    void accountToCreateShouldBeNotifiedTo() {
 9        // Arrange
10        ExternalSystem externalSystem = mock(ExternalSystem.class);
11        Accounts accounts = new Accounts();
12        accounts.addExternalSystem(externalSystem);
13
14        AccountToCreate accountToCreate = new AccountToCreate("john.doe@acme.com");
15
16        // Act
17        accounts.create(accountToCreate);
18
19        // Assert
20        verify(externalSystem).receive(accountToCreate);
21    }
22
23}