What Is Mockito?
Mockito
Mockito is a framework that makes it easy to create, manage, and verify mock objects in Java tests.
A mock is a fake object used for testing. Mockito can create a mock of a specified class, stub any method to return a specified value, and verify whether a mock method was called as expected. One of its strengths is that mock behavior can be defined in a type-safe style.
HelloWorld
Add Mockito as a test dependency, for example org.mockito:mockito-core. Then create a mock object with mock() and define behavior with when(...).thenReturn(...).
List<String> mock = mock(List.class);
when(mock.get(0)).thenReturn("Hello Mockito!");
Here, a mock java.util.List is created, and get(0) is defined to return "Hello Mockito!".
Default Mock Behavior
Methods on a mock return default values if they are not stubbed. Primitive values return zero-like values, collections can return empty collections, and object references generally return null.
Creating Stubs with when
Use the following form to specify the value returned by a mock method.
when(<method call to stub>).thenReturn(<method return value>)
Once a method is stubbed, it returns the same value every time unless another stub overrides it.
Returning Different Values on Each Call
Use the varargs form thenReturn(T...) to return a different value for each call. If the method is called more times than the number of specified values, Mockito keeps returning the last value.
Throwing Exceptions
Use thenThrow(Throwable...) to make a stub throw exceptions. The varargs form can throw different exceptions on consecutive calls, and after the specified exceptions are exhausted, the last exception keeps being thrown.
Combining Return Values and Exceptions
Mockito can also combine return values and thrown exceptions for consecutive calls.
Matching Arbitrary Arguments
Use methods from ArgumentMatchers, such as anyInt(), anyList(), or any(), to define stubs for arbitrary arguments.
When a method has multiple arguments, if one argument uses a matcher, all other arguments must also be provided by matchers. Use eq() when you want to match a specific value while using matchers for other arguments.
Custom Argument Matching
Custom matchers can be used when built-in matchers are not enough.
Running Arbitrary Logic in a Stub
Use thenAnswer() when a stub needs to execute arbitrary logic. Mockito also provides typed answer helpers such as Answer1 through Answer6. Avoid overusing complex stubs because they can make tests harder to understand and maintain. The official documentation recommends using thenReturn() and thenThrow() whenever possible.
Stubbing void Methods
For void methods, use stubbing methods that start with doThrow() when you want the method to throw an exception.
Verifying Method Calls
Use verify() to check whether a method was called. Verification includes arguments.
Mockito can verify:
- Whether a method was called with matching arguments.
- How many times a method was called.
- Whether it was called at least or at most a given number of times.
- Whether it was never called.
- The order of method calls with
InOrder. - The order of calls across multiple mocks.
- Actual arguments passed to a method with
ArgumentCaptor.
Spy
A spy is based on a real object. If a spy method is not stubbed, the real method is executed. The spy is created from a copy of the original object, so changes to the spy and original object are not always shared.
When stubbing a spy, when(spy.method()) can call the real method during stubbing. Use doReturn().when(spy).method() to avoid calling the real method. Use doThrow() if you want to stub a spy method to throw an exception without executing the real method.
Mockito can also create spies for abstract classes with spy(Class), provided that the target class has a default constructor.
Delegating to Another Object
AdditionalAnswers.delegatesTo() can create a mock or spy-like object that delegates calls to another object. The delegate does not need to inherit from the mocked type.
Serializable Mocks
Mockito can create serializable mocks by using withSettings().serializable().
One-Liner Mock and Stub
Mockito can create a mock and define its stub in a compact one-liner, but use this style carefully so tests remain readable.
Defining Mocks with Annotations
Mockito supports field annotations such as @Mock, @Spy, and @Captor. Initialize them with Mockito’s annotation support. For JUnit 5, add mockito-junit-jupiter and use MockitoExtension; mocks can also be received as method parameters.
Inline Mock Maker
The inline mock maker enables features that ordinary Mockito cannot provide, such as mocking final classes and stubbing static methods. Add the org.mockito:mockito-inline dependency.
With inline mock maker, you can:
- Mock and stub final classes and methods.
- Stub static methods with
Mockito.mockStatic(Class). - Return mocks from constructors with
mockConstruction().
Constructor mocking is valid only until the returned MockedConstruction is closed. Stubbing and verification use ordinary Mockito APIs such as when() and verify().
Classes That Must Not Be Mocked
Mockito provides @DoNotMock to mark classes that should not be mocked. If such a class is mocked, Mockito fails and asks you to create a real instance instead.