Mockito
mockito mockito creates test doubles — mocks that record interactions and stubs return values. combined with junit 5, it lets you unit-test
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:
@ExtendWith(MockitoExtension.class)class UserServiceTest {@Mock UserRepository repo;@Mock EmailService email;@InjectMocks UserService service;@Testvoid 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
- Understand the core idea behind Mockito.
- Walk through the runnable example and tweak it in the playground.
- Apply the pattern in a small Spring Boot or CLI exercise of your own.
- Re-read the common mistakes and interview Q&A to lock the concept in.
Interactive workflow diagram
Identify use case
Recognize when mockito is the right tool for the problem.
Useful template
Mockito stub + verify
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.
Q2When would you avoid Mockito?
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.