🎯 What you will learn
Mockito is the most widely used mocking framework for Java. It lets you replace real dependencies — databases, HTTP clients, email gateways — with controlled fakes so you can test a single class in isolation. By the end of this lesson you will understand:
@Mockto create fake implementations of interfaces and classes@ExtendWith(MockitoExtension.class)to activate Mockito in JUnit 5when(mock.method()).thenReturn(value)to stub return valuesverify(mock, times(n)).method(args)to assert interactionsnever(),any(),eq(),contains(),argThat()matchersdoThrow()for void methods and error-path testing- The difference between
@Mockand@Spy
💼 Real-world scenario
TaxFilingService depends on ITRRepository (database) and NotificationService (email gateway). Rohan replaces both with Mockito mocks — no real DB, no real emails. He stubs hasFiled() to return false/true, then verifies that save() and send() are called with the right arguments.
🎭 @Mock, @ExtendWith, when/thenReturn
The AAA pattern — Arrange (stub the mock), Act (call the real service), Assert (check the result). @ExtendWith(MockitoExtension.class) initialises all @Mock fields before each test.
AAA pattern: Arrange — set up the mock's stubbed behaviour. Act — call the method under test. Assert — check return values and, if needed, verify interactions. Keep the three sections visually separated in every test for readability.
✅ verify() interactions
verify(mock) asserts that a method was called. verify(mock, times(n)) checks exact call count. verify(mock, never()) asserts the method was never called — critical for error path tests.
🔬 Argument matchers + doThrow
Argument matchers let you match method calls flexibly. You must use matchers for all arguments or none — never mix raw values and matchers in the same call (use eq() to wrap a literal).
@Spy vs @Mock: @Mock fakes all methods — every method returns a default (null, 0, false) unless stubbed. @Spy wraps a real object and only intercepts methods you explicitly stub; the rest call the real implementation. Use @Mock for full control; @Spy when you want mostly real behaviour with one or two stubbed methods.
📋 Mockito quick reference
| Operation | Syntax | Purpose |
|---|---|---|
| Stub return value | when(mock.method(args)).thenReturn(value) | Arrange step — define fake response |
| Stub exception | when(mock.method(args)).thenThrow(new Ex()) | Test error paths for non-void methods |
| Stub void method | doThrow(new Ex()).when(mock).method(args) | Void methods can't use when() directly |
| Verify call count | verify(mock, times(n)).method(args) | Assert method called n times |
| Verify never called | verify(mock, never()).method(any()) | Assert method was not invoked |
| Any argument | any(), anyString(), anyInt() | Match any value of that type |
| Exact value | eq("literal") | Match exact value when mixing matchers |
| Custom predicate | argThat(obj -> condition) | Match by arbitrary logic |
🎤 Interview Q&A
Arrange: set up the object under test and stubs. Act: call the method being tested. Assert: verify the return value, state change, or interactions. The three sections should be visually separated in every test for readability.
Mockito returns "nice" defaults: null for objects, 0 for numbers, false for booleans, empty collections for List/Set/Map. Unstubbed calls don't throw — they silently return defaults.
@InjectMocks tells Mockito to construct the class under test and inject all @Mock and @Spy fields into it (by constructor, setter, or field injection). Use it for convenience, but be careful: if injection fails silently, the field stays null and tests give misleading NullPointerExceptions.
when(method).thenReturn(value) makes the mock return the value. when(method).thenThrow(new RuntimeException()) makes it throw. Use thenThrow to test error paths.
Mockito uses ByteBuddy to generate a subclass (or proxy) of the target class at runtime. The generated class overrides every method to: record the call arguments, check for matching stubs, return the stubbed value (or default), and add the call to the invocation log for verify(). This is why Mockito requires the JVM to allow dynamic class loading — on JDK 21+ it needs the byte-buddy-agent.jar dynamically attached.
📝 Quiz — 5 questions
Next: Integration Tests with Testcontainers →
⚠️ Common mistakes
verify(notifier).send("PAN001", anyString()) mixes a raw value with a matcher. Mockito requires all arguments to use matchers or none. Fix: verify(notifier).send(eq("PAN001"), anyString()).when(repo.save(x)) won't compile for void methods. Use doNothing().when(repo).save(any()) or doThrow().when(repo).save(any()).verify(calculator) when you meant verify(repository) silently passes if calculator has any matching method. Always verify the object you care about.✅ Key takeaways
- @Mock creates a fake; @Spy wraps a real object; @ExtendWith(MockitoExtension.class) enables both
- when(mock.method()).thenReturn(value) stubs a response (Arrange step)
- verify(mock, times(1)).method(args) checks interactions (Assert step)
- never() asserts a method was not called — critical for error path tests
- Mix raw values and matchers with eq() — never mix matchers and raw values in the same call
From mocked services to production-grade Java
Join the Best AI Programs — three 5-month courses, fully online, with placement assistance. Week 1 is free.
Explore our AI-era courses →