1. Concept library
  2. Java & Spring Boot
  3. Module 5: Build tools and testing

Concept

Mocking with Mockito

A mock stands in for a collaborator so a unit test can control what it returns and check how it was called. It keeps tests fast and focused on the class under test.

What a session covers

The tutor works through these with you, in conversation and code. A session ends when you have shown them, not when a video does.

  1. Explain what a mock stands in for and what it should not replace
  2. Write a test that stubs a collaborator and verifies a call
  3. Spot the test that only verifies its own mocks

In practice

A few lines that show Mocking with Mockito doing its job.

Java
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
    @Mock PaymentGateway payments;
    @Mock OrderRepository orders;
    @InjectMocks OrderService service;

    @Test
    void chargesThenSaves() {
        when(payments.charge(1999)).thenReturn(new Charge("ch_1"));
        service.place(new Order(1999));
        verify(orders).save(argThat(o -> o.chargeId().equals("ch_1")));
    }
}

The common mistake

Watch for

Mocking the class under test, or mocking value objects and repositories so thoroughly that the test only verifies the mocks. Mock the boundaries, use real objects for the rest.

What to know first

Your roadmap puts these before Mocking with Mockito, unless you already know them.

How it stays learned

Once a session shows you understand Mocking with Mockito, it comes back for review. Each review takes a minute and tells the memory model how well you still know it.

  1. Day 3First recall, while it is fresh
  2. Day 7Second, a week on
  3. Day 18Last, when it has settled
Previous in the module← JUnit tests