Skip to content
Tutorials Center
My learning

Topics

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

  1. 1 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.
  2. 2 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.
  3. 3 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.
  4. 4 How Mocks Work Inside Understand what happens when you call mock(): generated classes, call interception, the stubbing registry and why constructors do not run.
  5. 5 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

  1. 6 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.
  2. 7 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.
  3. 8 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.
  4. 9 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.
  5. 10 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

  1. 11 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.
  2. 12 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.
  3. 13 verifyNoMoreInteractions and verifyNoInteractions Catch unexpected calls with verifyNoMoreInteractions and verifyNoInteractions, understand what counts as verified, and learn why overusing them makes tests brittle.
  4. 14 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

  1. 15 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.
  2. 16 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.
  3. 17 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.
  4. 18 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

  1. 19 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.
  2. 20 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.
  3. 21 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.
  4. 22 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

  1. 23 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.
  2. 24 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.
  3. 25 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

  1. 26 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.
  2. 27 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.
  3. 28 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.
  4. 29 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

  1. 30 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.
  2. 31 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.
  3. 32 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.
  4. 33 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

  1. 34 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.
  2. 35 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.
  3. 36 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.
  4. 37 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.