Mockito mock objects library core API and implementation for comprehensive Java unit testing
—
This section covers creating and configuring mock objects, spies, and advanced mock settings in Mockito.
Create mock instances of classes or interfaces.
public static <T> T mock(Class<T> classToMock)
public static <T> T mock(Class<T> classToMock, String name)
public static <T> T mock(Class<T> classToMock, Answer defaultAnswer)
public static <T> T mock(Class<T> classToMock, MockSettings settings)
// Parameterless mock creation (since 4.10.0)
public static <T> T mock(T... reified)
public static <T> T mock(Answer defaultAnswer, T... reified)
public static <T> T mock(String name, T... reified)
public static <T> T mock(MockSettings settings, T... reified)Usage Examples:
// Basic mock creation
List<String> mockList = mock(List.class);
UserService mockUserService = mock(UserService.class);
// Named mock for better error messages
List<String> namedMock = mock(List.class, "userList");
// Mock with custom default answer
List<String> mockWithAnswer = mock(List.class, RETURNS_SMART_NULLS);
// Parameterless mock creation (automatic type detection)
List<String> autoMock = mock();
UserService autoUserService = mock();
// Parameterless with custom settings
List<String> customAutoMock = mock(RETURNS_SMART_NULLS);
List<String> namedAutoMock = mock("myList");Create spies that wrap real objects, calling real methods unless stubbed.
public static <T> T spy(T object)
public static <T> T spy(Class<T> classToSpy)
// Parameterless spy creation (since 4.10.0)
public static <T> T spy(T... reified)Usage Examples:
// Spy on existing object
List<String> realList = new ArrayList<>();
List<String> spyList = spy(realList);
// Spy on class (calls real constructor)
List<String> classSpy = spy(ArrayList.class);
// Parameterless spy creation (automatic type detection)
List<String> autoSpy = spy();
// Partial stubbing with spy
when(spyList.size()).thenReturn(100);
spyList.add("real method called");Advanced configuration for mock creation.
public static MockSettings withSettings()
interface MockSettings {
MockSettings name(String name);
MockSettings defaultAnswer(Answer defaultAnswer);
MockSettings extraInterfaces(Class<?>... interfaces);
MockSettings serializable();
MockSettings serializable(SerializableMode mode);
MockSettings spiedInstance(Object spiedInstance);
MockSettings useConstructor(Object... constructorArgs);
MockSettings outerInstance(Object outerClassInstance);
MockSettings strictness(Strictness strictness);
MockSettings mockMaker(String mockMaker);
@Deprecated MockSettings lenient();
MockSettings invocationListeners(InvocationListener... listeners);
MockSettings verificationStartedListeners(VerificationStartedListener... listeners);
MockSettings stubbingLookupListeners(StubbingLookupListener... listeners);
MockSettings stubOnly();
MockSettings withoutAnnotations();
MockSettings verboseLogging();
MockSettings genericTypeToMock(Type genericTypeToMock);
<T> MockCreationSettings<T> build(Class<T> typeToMock);
<T> MockCreationSettings<T> buildStatic(Class<T> classToMock);
}Usage Examples:
// Mock with multiple interfaces
Foo mockFoo = mock(Foo.class, withSettings()
.extraInterfaces(Bar.class, Baz.class)
.name("fooMock"));
// Serializable mock
List<String> serializableMock = mock(List.class, withSettings()
.serializable());
// Mock with constructor arguments
UserService userService = mock(UserService.class, withSettings()
.useConstructor("database-url", 30));
// Lenient mock (bypasses strict stubbing)
List<String> lenientMock = mock(List.class, withSettings()
.lenient());Inspect mock objects and their configuration.
public static MockingDetails mockingDetails(Object toInspect)
interface MockingDetails {
boolean isMock();
boolean isSpy();
Object getMock();
Collection<Invocation> getInvocations();
Collection<Stubbing> getStubbings();
MockCreationSettings<?> getMockCreationSettings();
MockHandler getMockHandler();
String printInvocations();
}Usage Examples:
List<String> mockList = mock(List.class);
MockingDetails details = mockingDetails(mockList);
if (details.isMock()) {
System.out.println("Object is a mock");
}
if (details.isSpy()) {
System.out.println("Object is a spy");
}
// Get the mock object itself
Object mockObject = details.getMock();
// Get invocation history
Collection<Invocation> invocations = details.getInvocations();
// Get stubbing information
Collection<Stubbing> stubbings = details.getStubbings();
// Get mock creation settings
MockCreationSettings<?> settings = details.getMockCreationSettings();
Class<?> mockedType = settings.getTypeToMock();
String mockName = settings.getName();
// Get mock handler (for advanced framework integration)
MockHandler handler = details.getMockHandler();
// Print detailed mock information for debugging
System.out.println(details.printInvocations());Reset mock objects to their initial state.
public static void reset(Object... mocks)Usage Example:
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(10);
// Use mock...
mockList.size(); // returns 10
// Reset removes all stubbing and interaction history
reset(mockList);
mockList.size(); // returns 0 (default)Clear only invocation history while preserving stubbing.
public static <T> void clearInvocations(T... mocks)Usage Example:
List<String> mockList = mock(List.class);
when(mockList.size()).thenReturn(10);
mockList.size(); // Invocation recorded
mockList.add("test"); // Another invocation
// Clear only invocations, keep stubbing
clearInvocations(mockList);
// Stubbing still works
assertEquals(10, mockList.size());
// But no previous invocations recorded for verification
verify(mockList, never()).add(anyString()); // PassesClear Mockito's internal caches and state.
public static void clearAllCaches()Usage Example:
// Clear all Mockito state (rarely needed)
clearAllCaches();Validate proper Mockito usage and detect potential issues.
public static void validateMockitoUsage()Usage Example:
@Test
void testWithValidation() {
// Test code with mocks...
// Validate at end of test
validateMockitoUsage();
}Make individual stubbings bypass strict stubbing validation.
public static LenientStubber lenient()Usage Example:
// Regular stubbing (subject to strict validation)
when(mock.someMethod()).thenReturn("value");
// Lenient stubbing (bypasses strict validation)
lenient().when(mock.someMethod()).thenReturn("value");
// Useful for stubbings that might not always be used
lenient().when(mock.optionalMethod()).thenReturn("fallback");Access Mockito's framework for advanced integrations.
public static MockitoFramework framework()Usage Example:
MockitoFramework framework = framework();
InvocationFactory invocationFactory = framework.getInvocationFactory();
// Access framework plugins
MockMaker mockMaker = framework.getPlugins().getMockMaker();Manage mock sessions for better test isolation.
public static MockitoSessionBuilder mockitoSession()Usage Example:
MockitoSession session = mockitoSession()
.initMocks(this)
.strictness(Strictness.STRICT_STUBS)
.logger(new CustomLogger())
.startMocking();
try {
// Test code with session-managed mocks
// ...
} finally {
session.finishMocking();
}Contains immutable mock creation configuration.
interface MockCreationSettings<T> {
Class<T> getTypeToMock();
Set<Class<?>> getExtraInterfaces();
String getName();
Object getSpiedInstance();
Answer<Object> getDefaultAnswer();
boolean isSerializable();
SerializableMode getSerializableMode();
List<InvocationListener> getInvocationListeners();
List<VerificationStartedListener> getVerificationStartedListeners();
boolean isStubOnly();
Strictness getStrictness();
boolean isLenient();
String getMockMaker();
Type getGenericTypeToMock();
Object getOuterClassInstance();
boolean isUsingConstructor();
Object[] getConstructorArgs();
}enum SerializableMode {
NONE,
BASIC,
ACROSS_CLASSLOADERS
}
enum Strictness {
LENIENT,
WARN,
STRICT_STUBS
}
// Default Answer implementations
Answer<Object> RETURNS_DEFAULTS
Answer<Object> RETURNS_SMART_NULLS
Answer<Object> RETURNS_MOCKS
Answer<Object> RETURNS_DEEP_STUBS
Answer<Object> CALLS_REAL_METHODS
Answer<Object> RETURNS_SELFFor advanced framework integrators.
interface MockHandler {
Object handle(Invocation invocation) throws Throwable;
MockCreationSettings<?> getMockSettings();
InvocationContainer getInvocationContainer();
}
interface InvocationContainer {
// Marker interface for internal implementation
}
interface LenientStubber extends Stubber {
// Extends Stubber with lenient behavior
}// Mock with all advanced settings
UserService mockUserService = mock(UserService.class, withSettings()
.name("userServiceMock")
.defaultAnswer(RETURNS_SMART_NULLS)
.extraInterfaces(Auditable.class, Cacheable.class)
.serializable(SerializableMode.ACROSS_CLASSLOADERS)
.strictness(Strictness.LENIENT)
.verboseLogging()
.invocationListeners(new CustomInvocationListener())
.verificationStartedListeners(new CustomVerificationListener())
.stubbingLookupListeners(new CustomStubbingListener()));
// Cast to extra interfaces
Auditable auditableMock = (Auditable) mockUserService;
Cacheable cacheableMock = (Cacheable) mockUserService;// Mock abstract class with constructor arguments
AbstractService mockService = mock(AbstractService.class, withSettings()
.useConstructor("database-url", 30, true)
.defaultAnswer(CALLS_REAL_METHODS));
// Mock inner class with outer instance
OuterClass outer = new OuterClass();
OuterClass.InnerClass mockInner = mock(OuterClass.InnerClass.class, withSettings()
.useConstructor()
.outerInstance(outer)
.defaultAnswer(CALLS_REAL_METHODS));// Mock with generic type information
List<String> mockList = mock(List.class, withSettings()
.genericTypeToMock(new TypeReference<List<String>>() {}.getType()));// Advanced framework integration
MockSettings advancedSettings = withSettings()
.name("frameworkMock")
.stubOnly() // Memory optimization
.mockMaker("custom-mock-maker");
MockCreationSettings<UserService> settings = advancedSettings.build(UserService.class);
MockHandler handler = mockingDetails(mock).getMockHandler();
// Create invocation factory for programmatic invocations
InvocationFactory invocationFactory = framework().getInvocationFactory();Install with Tessl CLI
npx tessl i tessl/maven-org-mockito--mockito-core