Mockito Tutorial
Learn Mockito step by step: 37 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Mockito? Learn what Mockito is, why Java tests need test doubles, how mocks differ from stubs and fakes, and what you can run on this site.
- Setting Up Mockito with Maven and Gradle Add Mockito to a Maven or Gradle project, learn which artifacts you need, how the inline mock maker works, and how to check your setup.
- Your First Mock Create your first Mockito mock with mock(), see which default values unstubbed methods return, and pass a mock into the class you want to test.
- How Mocks Work Inside Understand what happens when you call mock(): generated classes, call interception, the stubbing registry and why constructors do not run.
- Mockito with JUnit and Annotations Use @ExtendWith(MockitoExtension.class), @Mock and @InjectMocks with JUnit Jupiter, learn how fields are initialised per test, and when to skip annotations.
Mocks and Stubs
- Stubbing Return Values with when and thenReturn Teach a Mockito mock what to return with when().thenReturn(): argument matching by equals, overriding stubs, returning objects and lists, and common mistakes.
- Stubbing Exceptions with thenThrow and doThrow Make Mockito mocks throw exceptions with thenThrow and doThrow to test error handling, retries and fallbacks, including checked exceptions and void methods.
- Consecutive Stubbing and Custom Answers Return different values on successive calls with chained thenReturn, then compute results from the arguments with thenAnswer for stateful and echoing mocks.
- Default Answers and Void Methods Control what unstubbed mock methods return with RETURNS_SMART_NULLS and deep stubs, and learn doReturn, doNothing, doThrow and doAnswer for void methods.
- InjectMocks and the Mock Annotations Learn how @InjectMocks builds the class under test: constructor, setter and field injection, matching by type and name, and when to construct by hand instead.
Verification
- Verification Basics with verify() Use Mockito verify() to assert that a mock was called, with which arguments and how often, and learn what is worth verifying and what is not.
- Verification Modes โ times, never, atLeast, atMost, timeout Check how often a mock was called with times, never, atLeast, atLeastOnce, atMost, only and timeout, and learn when each mode is the right choice.
- verifyNoMoreInteractions and verifyNoInteractions Catch unexpected calls with verifyNoMoreInteractions and verifyNoInteractions, understand what counts as verified, and learn why overusing them makes tests brittle.
- Verifying Call Order with InOrder Use Mockito InOrder to verify that calls happen in a given sequence, across one or several mocks, and learn what it ignores, when order matters and how it fails.
Argument Matchers and Captors
- Argument Matchers โ any(), eq(), anyString() Stub and verify without spelling out every value using Mockito argument matchers such as any, anyString, anyInt, eq, isNull and startsWith, and how null is treated.
- The Matcher Rules โ All or None, and eq() Learn the all-or-none rule for Mockito argument matchers, how eq() fixes mixed arguments, why misplaced matchers leak, and how to avoid NPEs with primitives.
- Custom Argument Matchers with argThat Write your own Mockito argument matchers with argThat and ArgumentMatcher lambdas, build reusable named matchers, and know when to use a captor instead.
- ArgumentCaptor โ Capture and Inspect Arguments Use Mockito ArgumentCaptor to grab the arguments passed to a mock, assert on their fields, collect values from several calls, and capture callbacks.
Spies and Partial Mocks
- Spies Basics Learn what a Mockito spy is, how it differs from a mock, how spy() and @Spy wrap a real object, and when a spy is the right test double to reach for.
- Stubbing Spies with doReturn Why when(spy.method()) can run the real method while stubbing, how doReturn, doThrow and doNothing avoid it, and when each style is the better choice.
- Partial Mocks and callRealMethod Build partial mocks in Mockito with CALLS_REAL_METHODS, thenCallRealMethod and doCallRealMethod, test abstract classes and template methods, and avoid the traps.
- Spy Self-Invocation and Pitfalls Understand how a Mockito spy handles calls made from inside the object, why the field copy surprises people, and the pitfalls with private, final and static methods.
Static and Final Mocking
- Final Classes and the Inline Mock Maker See why mocking libraries once could not mock final classes and methods, how Mockito 5's inline mock maker changed that, and when a wrapper is still the better design.
- Mocking Static Methods Learn how Mockito's mockStatic works with try-with-resources and thread scope, when it is justified, and how a seam or wrapper often makes the test simpler.
- Mocking Constructors and Time Use Mockito's mockConstruction to replace objects created with new, then learn the cleaner alternatives: factories and java.time.Clock for deterministic time in tests.
Strictness and Extensions
- Strict Stubs and Unnecessary Stubbing Learn what Mockito's strictness does, why UnnecessaryStubbingException and PotentialStubbingProblem appear, the three strictness levels, and how to fix tests cleanly.
- JUnit 5 Extension and Annotations How @ExtendWith(MockitoExtension.class), @Mock, @InjectMocks, @Spy and @Captor work, how injection picks constructor, setter or field, and the older runner and openMocks options.
- Mock Settings and Default Answers Configure mocks with withSettings(), choose a default answer such as RETURNS_SMART_NULLS or RETURNS_DEEP_STUBS, write custom Answers, and name mocks for clearer errors.
- BDD Style and Lenient Stubbing Write Mockito tests in given-when-then form with BDDMockito, learn when lenient stubbing is the right escape from strict stubs, and how to keep shared setup clean.
Patterns and Pitfalls
- Over-Mocking and Test Smells Spot the signs of over-mocked tests: brittle interaction checks, mocked value objects, mocks of the class under test. Learn what to mock, what to keep real, and how to refactor.
- Deep Stubs and the Law of Demeter Understand Mockito's RETURNS_DEEP_STUBS for chained calls, why a test that needs it signals a Law of Demeter violation, and how to refactor so ordinary stubs are enough.
- Fakes, Stubs and Mocks: Choosing Compare dummies, stubs, fakes, spies and mocks with runnable Java, learn when an in-memory fake beats a Mockito mock, and get a checklist for picking the right double.
- Troubleshooting Common Mockito Errors Decode the Mockito errors you will meet: NullPointerException on mocks, stubs that do not match, UnfinishedStubbing, InvalidUseOfMatchers, WrongTypeOfReturnValue and more, with causes and fixes.
Projects and Practice
- Project: Order Service Tests Build and test an order checkout service with an inventory, a payment gateway, a repository and a mailer: stubs for inputs, verified effects, failure paths and compensation.
- Project: Notification Dispatcher Test a dispatcher that tries channels in order, falls back on failure, respects quiet hours with an injected Clock, and never contacts a channel it should skip.
- Project: Payment Retry with Backoff Test a retry mechanism without sleeping: consecutive stubbing with thenThrow then thenReturn, an injected Sleeper, permanent versus transient errors, and exact call counts.
- Practice: Mockito Exercises Eight hands-on Mockito exercises on spies, partial mocks, static and time seams, strict stubs and test design, with runnable stand-in solutions and real Mockito answers.