Java Tutorial 0/145 lessons ~6 min read Lesson 76

    Mockito

    mockito mockito creates test doubles — mocks that record interactions and stubs return values. combined with junit 5, it lets you unit-test

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    Introduction

    Mockito creates test doubles — mocks that record interactions and stubs return values. Combined with JUnit 5, it lets you unit-test a class in isolation without spinning up Spring or a database.

    Informative example

    Mock, stub, verify:

    ts
    @ExtendWith(MockitoExtension.class)
    class UserServiceTest {
    @Mock UserRepository repo;
    @Mock EmailService email;
    @InjectMocks UserService service;
    @Test
    void registersUser() {
    var req = new RegisterRequest("ada@example.com", "secret");
    when(repo.existsByEmail("ada@example.com")).thenReturn(false);
    when(repo.save(any())).thenAnswer(i -> i.getArgument(0));
    User user = service.register(req);
    assertThat(user.email()).isEqualTo("ada@example.com");
    verify(email).sendWelcome("ada@example.com");
    verify(repo, never()).delete(any());
    }
    }

    Best practices

    • Mock external dependencies only — not the class under test.
    • Use @InjectMocks for the SUT; @Mock for collaborators.
    • Prefer verify over assert on mock return values when testing interactions.

    Purpose of this lesson

    Master Mockito so you can apply it confidently in production Java code, technical interviews, and code reviews.

    Step-by-step explanation

    1. Understand the core idea behind Mockito.
    2. Walk through the runnable example and tweak it in the playground.
    3. Apply the pattern in a small Spring Boot or CLI exercise of your own.
    4. Re-read the common mistakes and interview Q&A to lock the concept in.

    Interactive workflow diagram

    1Mockito — typical flow
    1 / 4

    Identify use case

    Recognize when mockito is the right tool for the problem.

    Useful template

    Mockito stub + verify

    java
    when(repo.findById(1L)).thenReturn(Optional.of(user));
    verify(repo, times(1)).save(any());
    verify(email, never()).send(any());

    Debugging tips

    • UnnecessaryStubbingException? Remove unused when() stubs or use @MockitoSettings(strictness = LENIENT).

    Optimization strategies

    • Profile before optimizing — JFR (Java Flight Recorder) and async-profiler reveal real hotspots.
    • Prefer immutable data and stream pipelines over hand-rolled loops when readability matters.
    • Reach for the right JDK collection (ArrayList vs LinkedList vs ArrayDeque) before writing custom data structures.

    Enterprise example

    Teams at Netflix, Uber and Goldman Sachs apply Mockito daily — usually wrapped behind Spring Boot services with observability hooks (Micrometer + OpenTelemetry).

    Interview questions & answers

    Q1Explain Mockito in one minute.
    Describe what problem it solves, the JDK APIs involved, and one production trade-off.
    Q2When would you avoid Mockito?
    Mention performance, complexity, or readability cases where a simpler approach wins.

    Summary

    In this lesson you learned Mockito — the concept, syntax, a runnable example, and the production pitfalls to avoid. Apply it in the playground before moving on.

    Ready to mark this lesson complete?Track your journey across the entire course.