or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

annotations.mdargument-capturing.mdbdd-testing.mdindex.mdjunit-integration.mdmatchers.mdmock-creation.mdstubbing.mdverification.md
tile.json

tessl/maven-org-mockito--mockito-all

A comprehensive Java mocking framework that enables developers to create test doubles for unit testing.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.mockito/mockito-all@1.10.x

To install, run

npx @tessl/cli install tessl/maven-org-mockito--mockito-all@1.10.0

index.mddocs/

Mockito

Mockito 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.

Package Information

  • Package Name: org.mockito:mockito-all
  • Package Type: Maven
  • Language: Java
  • Version: 1.10.19
  • Installation: Add to Maven dependencies:
    <dependency>
      <groupId>org.mockito</groupId>
      <artifactId>mockito-all</artifactId>
      <version>1.10.19</version>
      <scope>test</scope>
    </dependency>
  • Gradle: 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.

Core Imports

import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

For BDD-style testing:

import static org.mockito.BDDMockito.*;

Basic Usage

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);
    }
}

Architecture

Mockito is built around several key components:

  • Mock Creation: Create mock objects of classes and interfaces using mock() and spy()
  • Stubbing API: Define behavior for mock methods using when().thenReturn() family
  • Verification System: Verify mock interactions with verify() and various verification modes
  • Argument Matching: Flexible argument matching with any(), eq(), and custom matchers
  • Annotation Support: Shorthand creation with @Mock, @Spy, @InjectMocks, and @Captor
  • BDD Integration: Behavior-driven development style with given().willReturn() syntax

Capabilities

Mock Creation and Spying

Core 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);

Mock Creation and Spying

Method Stubbing

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);

Method Stubbing

Verification and Interaction Testing

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);

Verification

Argument Matching

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);

Argument Matching

Annotation-Based Testing

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 { }

Annotations

Argument Capturing

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();
}

Argument Capturing

BDD-Style Testing

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);

BDD Style Testing

JUnit Integration

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();
}

JUnit Integration

Mock Utilities

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();

Exception Handling

Mockito provides comprehensive exception types for different error scenarios:

  • MockitoException: Base exception for framework errors
  • InvalidUseOfMatchersException: Incorrect argument matcher usage
  • MissingMethodInvocationException: Missing method call in stubbing
  • WantedButNotInvoked: Expected method not called during verification
  • TooManyActualInvocations: More method calls than expected

Version Features

Version 1.8.0+

  • Argument capturing with ArgumentCaptor
  • Real partial mocks
  • Mock resetting capabilities
  • Framework usage validation

Version 1.9.0+

  • Automatic @Spy/@InjectMocks instantiation
  • One-liner stubs
  • Verification ignoring stubs

Version 1.10.0+

  • BDD style verification with then()
  • Abstract class mocking and spying (1.10.12+)

Types

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();
}