CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-mockito--mockito-core

Mockito mock objects library core API and implementation for comprehensive Java unit testing

Pending
Overview
Eval results
Files

stubbing.mddocs/

Method Stubbing and Behavior

This section covers configuring mock object behavior through stubbing, including return values, exceptions, custom answers, and consecutive calls.

Basic Stubbing

When-Then Stubbing

Configure method behavior using the when().then...() pattern.

public static <T> OngoingStubbing<T> when(T methodCall)

interface OngoingStubbing<T> {
    OngoingStubbing<T> thenReturn(T value);
    OngoingStubbing<T> thenReturn(T value, T... values);
    OngoingStubbing<T> thenThrow(Throwable... throwables);
    OngoingStubbing<T> thenThrow(Class<? extends Throwable> throwableType);
    OngoingStubbing<T> thenThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... nextToBeThrown);
    OngoingStubbing<T> thenCallRealMethod();
    OngoingStubbing<T> thenAnswer(Answer<?> answer);
    T getMock();
}

Usage Examples:

List<String> mockList = mock(List.class);

// Return specific value
when(mockList.get(0)).thenReturn("first");
when(mockList.size()).thenReturn(1);

// Return consecutive values
when(mockList.get(anyInt()))
    .thenReturn("first")
    .thenReturn("second")
    .thenReturn("third");

// Alternative syntax for consecutive values
when(mockList.get(anyInt())).thenReturn("first", "second", "third");

// Throw exception
when(mockList.get(999)).thenThrow(new IndexOutOfBoundsException());
when(mockList.clear()).thenThrow(UnsupportedOperationException.class);

Do-Family Stubbing

Do-When Stubbing

Alternative stubbing syntax, especially useful for void methods and spies.

public static Stubber doReturn(Object toBeReturned)
public static Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext)
public static Stubber doThrow(Throwable... toBeThrown)
public static Stubber doThrow(Class<? extends Throwable> toBeThrown)
public static Stubber doThrow(Class<? extends Throwable> toBeThrown, Class<? extends Throwable>... toBeThrownNext)
public static Stubber doAnswer(Answer answer)
public static Stubber doNothing()
public static Stubber doCallRealMethod()

interface Stubber {
    <T> T when(T mock);
    Stubber doReturn(Object toBeReturned);
    Stubber doReturn(Object toBeReturned, Object... toBeReturnedNext);
    Stubber doThrow(Throwable... toBeThrown);
    Stubber doThrow(Class<? extends Throwable> toBeThrown);
    Stubber doAnswer(Answer answer);
    Stubber doNothing();
    Stubber doCallRealMethod();
}

Usage Examples:

List<String> mockList = mock(List.class);

// Stub void method
doNothing().when(mockList).clear();
doThrow(new RuntimeException()).when(mockList).clear();

// Useful for spies (avoids calling real method)
List<String> spy = spy(new ArrayList<>());
doReturn("stubbed").when(spy).get(0); // doesn't call real get()

// Chain multiple behaviors
doReturn("first")
    .doReturn("second")
    .doThrow(new RuntimeException())
    .when(mockList).get(anyInt());

Custom Answers

Answer Interface

Provide custom logic for method invocations.

interface Answer<T> {
    T answer(InvocationOnMock invocation) throws Throwable;
}

interface InvocationOnMock {
    Object getMock();
    Method getMethod();
    Object[] getArguments();
    <T> T getArgument(int index);
    <T> T getArgument(int index, Class<T> clazz);
    Object callRealMethod() throws Throwable;
}

Usage Examples:

List<String> mockList = mock(List.class);

// Custom answer with access to arguments
when(mockList.get(anyInt())).thenAnswer(invocation -> {
    int index = invocation.getArgument(0);
    return "element-" + index;
});

// Answer that calls real method with modified arguments
UserService spy = spy(new UserService());
when(spy.findUser(anyString())).thenAnswer(invocation -> {
    String name = invocation.getArgument(0);
    return invocation.callRealMethod(name.toLowerCase());
});

// Answer using lambda for simple cases
when(mockList.size()).thenAnswer(inv -> 42);

Typed Answers

Type-safe answer interfaces for methods with specific parameter counts.

interface Answer1<T, A0> {
    T answer(A0 argument0) throws Throwable;
}

interface Answer2<T, A0, A1> {
    T answer(A0 argument0, A1 argument1) throws Throwable;
}

interface VoidAnswer1<A0> {
    void answer(A0 argument0) throws Throwable;
}
// ... up to Answer6 and VoidAnswer6

Usage Examples:

UserService mockService = mock(UserService.class);

// Type-safe answer
Answer1<User, String> userFinder = name -> new User(name);
when(mockService.findUser(anyString())).thenAnswer(userFinder);

// Void answer
VoidAnswer1<String> logger = message -> System.out.println("Log: " + message);
doAnswer(logger).when(mockService).log(anyString());

Advanced Stubbing

Lenient Stubbing

Bypass strict stubbing validation for specific stubs.

public static LenientStubber lenient()

interface LenientStubber extends Stubber {
    // Same methods as Stubber
}

Usage Example:

// Lenient stubbing won't fail on unused stubs
lenient().when(mockList.get(0)).thenReturn("first");
lenient().when(mockList.get(1)).thenReturn("second");
// Even if get(1) is never called, test won't fail

Consecutive Calls

Configure different behaviors for consecutive method calls.

Usage Examples:

// Using thenReturn with multiple values
when(mockList.get(0))
    .thenReturn("first")
    .thenReturn("second")
    .thenThrow(new RuntimeException());

// Using doReturn chain
doReturn("first")
    .doReturn("second")
    .doThrow(new RuntimeException())
    .when(mockList).get(0);

// Iterator-style stubbing
when(mockIterator.hasNext())
    .thenReturn(true)
    .thenReturn(true)
    .thenReturn(false);

Argument-Dependent Stubbing

Different behavior based on method arguments.

Usage Examples:

Map<String, String> mockMap = mock(Map.class);

// Different returns for different arguments
when(mockMap.get("key1")).thenReturn("value1");
when(mockMap.get("key2")).thenReturn("value2");
when(mockMap.get(argThat(key -> key.startsWith("error"))))
    .thenThrow(new IllegalArgumentException());

// Using argument matchers
when(mockMap.get(anyString())).thenReturn("default");
when(mockMap.get(startsWith("special"))).thenReturn("special-value");

Stubbing Verification

Stubbing Information

Access information about configured stubs.

interface StubbingInfo {
    InvocationOnMock getInvocation();
    boolean wasUsed();
}

Usage Example:

List<String> mockList = mock(List.class);
when(mockList.get(0)).thenReturn("stubbed");

MockingDetails details = mockingDetails(mockList);
Collection<StubbingInfo> stubbings = details.getStubbings();

for (StubbingInfo stub : stubbings) {
    System.out.println("Stub used: " + stub.wasUsed());
}

Install with Tessl CLI

npx tessl i tessl/maven-org-mockito--mockito-core

docs

additional-answers.md

additional-matchers.md

advanced-features.md

annotations.md

argument-matching.md

bdd-testing.md

index.md

mock-creation.md

static-mocking.md

stubbing.md

verification.md

tile.json