A comprehensive Java mocking framework that enables developers to create test doubles for unit testing.
npx @tessl/cli install tessl/maven-org-mockito--mockito-all@1.10.0Mockito is a comprehensive Java mocking framework that enables developers to create test doubles for unit testing. It provides a clean and simple API for creating mocks, stubs, and spies, allowing developers to verify interactions, stub method calls, and write readable tests with clear verification error messages.
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.10.19</version>
<scope>test</scope>
</dependency>testCompile 'org.mockito:mockito-all:1.10.19'Note: For newer projects, consider using org.mockito:mockito-core instead of mockito-all. The mockito-all artifact includes all dependencies bundled together, while mockito-core provides better dependency management flexibility.
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;For BDD-style testing:
import static org.mockito.BDDMockito.*;import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;
import java.util.List;
public class MockitoExampleTest {
@Test
public void testMockCreationAndVerification() {
// Create mock
List<String> mockedList = mock(List.class);
// Use mock object
mockedList.add("one");
mockedList.clear();
// Verification
verify(mockedList).add("one");
verify(mockedList).clear();
}
@Test
public void testStubbing() {
// Create mock
List<String> mockedList = mock(List.class);
// Stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
// Usage
System.out.println(mockedList.get(0)); // prints "first"
// Verification
verify(mockedList).get(0);
}
}Mockito is built around several key components:
mock() and spy()when().thenReturn() familyverify() and various verification modesany(), eq(), and custom matchers@Mock, @Spy, @InjectMocks, and @Captorgiven().willReturn() syntaxCore functionality for creating mock objects and spies. Supports mocking classes, interfaces, and creating partial mocks through spying on real objects.
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 mockSettings);
public static <T> T spy(T object);
public static <T> T spy(Class<T> classToSpy);
public static MockSettings withSettings();
public static MockingDetails mockingDetails(Object toInspect);Define behavior for mock method calls including return values, exceptions, and custom answers. Supports both traditional and BDD-style stubbing syntax.
public static <T> OngoingStubbing<T> when(T methodCall);
public static Stubber doReturn(Object toBeReturned);
public static Stubber doThrow(Throwable toBeThrown);
public static Stubber doAnswer(Answer answer);
public static Stubber doNothing();
public static Stubber doCallRealMethod();
// AdditionalAnswers utility methods
public static <T> Answer<T> returnsFirstArg();
public static <T> Answer<T> returnsSecondArg();
public static <T> Answer<T> returnsLastArg();
public static <T> Answer<T> returnsArgAt(int position);
public static <T> Answer<T> delegatesTo(Object delegate);
public static <T> Answer<T> returnsElementsOf(Collection<?> elements);Verify that mock methods were called with expected arguments and frequencies. Includes ordered verification and comprehensive verification modes.
public static <T> T verify(T mock);
public static <T> T verify(T mock, VerificationMode mode);
public static VerificationMode times(int wantedNumberOfInvocations);
public static VerificationMode never();
public static VerificationMode atLeastOnce();
public static VerificationMode atLeast(int minNumberOfInvocations);
public static VerificationMode atMost(int maxNumberOfInvocations);
public static VerificationMode only();
public static VerificationMode calls(int wantedNumberOfInvocations);
public static VerificationWithTimeout timeout(long millis);
public static VerificationAfterDelay after(int millis);
public static void verifyNoMoreInteractions(Object... mocks);
public static void verifyZeroInteractions(Object... mocks);
public static InOrder inOrder(Object... mocks);
public static Object[] ignoreStubs(Object... mocks);Flexible argument matching for stubbing and verification, including built-in matchers for common types and custom matcher support.
// Basic matchers
public static <T> T any();
public static <T> T any(Class<T> clazz);
public static <T> T eq(T value);
public static <T> T same(T value);
public static <T> T isNull();
public static <T> T isNotNull();
// Primitive type matchers
public static String anyString();
public static int anyInt();
public static long anyLong();
public static double anyDouble();
public static boolean anyBoolean();
// Collection matchers
public static List anyList();
public static <T> List<T> anyListOf(Class<T> clazz);
public static Set anySet();
public static Map anyMap();
public static Collection anyCollection();
// String matchers
public static String contains(String substring);
public static String matches(String regex);
public static String startsWith(String prefix);
public static String endsWith(String suffix);
// Custom matchers
public static <T> T argThat(Matcher<T> matcher);
// AdditionalMatchers comparison and logical
public static <T> T not(T value);
public static <T> T or(T left, T right);
public static <T> T and(T left, T right);
public static <T extends Comparable<T>> T geq(T value);
public static <T extends Comparable<T>> T leq(T value);
public static <T extends Comparable<T>> T gt(T value);
public static <T extends Comparable<T>> T lt(T value);Streamlined test setup using annotations for mock creation, spy creation, and dependency injection with automatic initialization.
@Target(FIELD) @Retention(RUNTIME)
public @interface Mock {
Answers answer() default Answers.RETURNS_DEFAULTS;
String name() default "";
Class<?>[] extraInterfaces() default {};
boolean serializable() default false;
}
@Target(FIELD) @Retention(RUNTIME)
public @interface Spy { }
@Target(FIELD) @Retention(RUNTIME)
public @interface InjectMocks { }
@Target(FIELD) @Retention(RUNTIME)
public @interface Captor { }Capture method arguments during verification for detailed assertions, supporting both single values and multiple invocations.
public class ArgumentCaptor<T> {
public static <T> ArgumentCaptor<T> forClass(Class<T> clazz);
public T capture();
public T getValue();
public List<T> getAllValues();
}Behavior-driven development syntax using given/when/then structure for more readable test specifications.
public static <T> BDDMyOngoingStubbing<T> given(T methodCall);
public static <T> BDDStubber willReturn(T value);
public static BDDStubber willThrow(Throwable... throwables);
public static <T> Then<T> then(T mock);Seamless integration with JUnit testing framework through runners and rules for automatic mock initialization and enhanced debugging.
public class MockitoJUnitRunner extends Runner;
public class VerboseMockitoJUnitRunner extends MockitoJUnitRunner;
public interface MockitoRule extends TestRule;
public class MockitoJUnit {
public static MockitoRule rule();
}Framework utilities for mock reset, stub management, and framework validation.
public static <T> void reset(T... mocks);
public static Object[] ignoreStubs(Object... mocks);
public static void validateMockitoUsage();Mockito provides comprehensive exception types for different error scenarios:
public interface Answer<T> {
T answer(InvocationOnMock invocation) throws Throwable;
}
public interface OngoingStubbing<T> {
OngoingStubbing<T> thenReturn(T value);
OngoingStubbing<T> thenReturn(T value, T... values);
OngoingStubbing<T> thenThrow(Throwable... throwables);
OngoingStubbing<T> thenAnswer(Answer<?> answer);
OngoingStubbing<T> thenCallRealMethod();
T getMock();
}
public interface Stubber {
<T> T when(T mock);
Stubber doReturn(Object toBeReturned);
Stubber doThrow(Throwable... toBeThrown);
Stubber doAnswer(Answer answer);
Stubber doNothing();
Stubber doCallRealMethod();
}
public interface VerificationMode { }
public interface VerificationWithTimeout extends VerificationMode {
VerificationMode atMost(int maxNumberOfInvocations);
VerificationMode never();
}
public interface VerificationAfterDelay extends VerificationMode { }
public interface InOrder {
<T> T verify(T mock);
<T> T verify(T mock, VerificationMode mode);
void verifyNoMoreInteractions();
}
public interface MockSettings {
MockSettings name(String name);
MockSettings defaultAnswer(Answer defaultAnswer);
MockSettings extraInterfaces(Class<?>... interfaces);
MockSettings serializable();
MockSettings serializable(SerializableMode mode);
MockSettings verboseLogging();
MockSettings spiedInstance(Object instance);
MockSettings invocationListeners(InvocationListener... listeners);
MockSettings stubOnly();
MockSettings useConstructor();
MockSettings outerInstance(Object outerClassInstance);
}
public enum Answers {
RETURNS_DEFAULTS,
RETURNS_SMART_NULLS,
RETURNS_MOCKS,
RETURNS_DEEP_STUBS,
CALLS_REAL_METHODS
}
public interface MockingDetails {
boolean isMock();
boolean isSpy();
Collection<Invocation> getInvocations();
}