CtrlK
BlogDocsLog inGet started
Tessl Logo

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

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

Pending
Overview
Eval results
Files

mock-creation.mddocs/

Mock Creation and Spying

Mockito provides several ways to create mock objects and spies for testing. Mocks are fake objects that record interactions, while spies are partial mocks that wrap real objects.

Mock Creation

Basic Mock Creation

Create a mock of any class or interface:

public static <T> T mock(Class<T> classToMock);

Usage Example:

List<String> mockedList = mock(List.class);
Map<String, Integer> mockedMap = mock(Map.class);
UserService mockedService = mock(UserService.class);

Named Mocks

Create mocks with custom names for better debugging:

public static <T> T mock(Class<T> classToMock, String name);

Usage Example:

List<String> mockedList = mock(List.class, "userList");
// Error messages will show "userList" instead of generic mock name

Mocks with Default Answers

Create mocks with predefined behavior for unstubbed methods:

public static <T> T mock(Class<T> classToMock, Answer defaultAnswer);

Usage Example:

List<String> mockedList = mock(List.class, RETURNS_SMART_NULLS);
UserService service = mock(UserService.class, CALLS_REAL_METHODS);

Mocks with Settings

Create mocks with advanced configuration options:

public static <T> T mock(Class<T> classToMock, MockSettings mockSettings);

Usage Example:

UserService service = mock(UserService.class, 
    withSettings()
        .name("userService")
        .defaultAnswer(RETURNS_SMART_NULLS)
        .extraInterfaces(Serializable.class)
        .serializable());

Deprecated Mock Creation

@Deprecated
public static <T> T mock(Class<T> classToMock, ReturnValues returnValues);

Spy Creation

Spying on Objects

Create a spy that wraps a real object:

public static <T> T spy(T object);

Usage Example:

List<String> realList = new ArrayList<>();
List<String> spyList = spy(realList);

// Real method is called
spyList.add("item");
assertEquals(1, spyList.size());

// Can stub methods
when(spyList.size()).thenReturn(100);
assertEquals(100, spyList.size());

Spying on Classes (v1.10.12+)

Create a spy of a class without providing an instance:

public static <T> T spy(Class<T> classToSpy);

Usage Example:

UserService spyService = spy(UserService.class);
// Mockito creates an instance using default constructor

Mock Settings Builder

Configure advanced mock behavior:

public static MockSettings withSettings();

public interface MockSettings {
    MockSettings name(String name);
    MockSettings defaultAnswer(Answer defaultAnswer);
    MockSettings extraInterfaces(Class<?>... interfaces);
    MockSettings serializable();
    MockSettings verboseLogging();
    MockSettings invocationListeners(InvocationListener... listeners);
    MockSettings spiedInstance(Object spiedInstance);
}

Usage Examples:

// Mock with multiple interfaces
Runnable mock = mock(Runnable.class, 
    withSettings().extraInterfaces(Serializable.class, Cloneable.class));

// Serializable mock
List<String> serializableMock = mock(List.class, 
    withSettings().serializable());

// Mock with verbose logging
UserService verboseService = mock(UserService.class, 
    withSettings().verboseLogging());

// Mock with custom default answer
Calculator calc = mock(Calculator.class, 
    withSettings().defaultAnswer(RETURNS_SMART_NULLS));

Answer Strategies

Control how unstubbed methods behave:

public static final Answer<Object> RETURNS_DEFAULTS;
public static final Answer<Object> RETURNS_SMART_NULLS;
public static final Answer<Object> RETURNS_MOCKS;
public static final Answer<Object> RETURNS_DEEP_STUBS;
public static final Answer<Object> CALLS_REAL_METHODS;

RETURNS_DEFAULTS

  • Returns null for objects, 0 for numbers, false for booleans
  • Empty collections for Collection types
  • Default behavior for mocks

RETURNS_SMART_NULLS

  • Returns SmartNull objects that provide helpful error messages
  • Helps identify NullPointerException sources in tests

RETURNS_MOCKS

  • Returns mocks for non-primitive return types
  • Useful for fluent interfaces and chaining

RETURNS_DEEP_STUBS

  • Automatically creates mock chains for method chaining
  • Example: mock.getFoo().getBar().getBaz() works without explicit stubbing

CALLS_REAL_METHODS

  • Calls real methods on the mock
  • Useful for partial mocking and spies

Best Practices

When to Use Mocks vs Spies

Use Mocks when:

  • Testing interactions with dependencies
  • Need complete control over behavior
  • Working with interfaces or abstract classes
  • Don't want real code execution

Use Spies when:

  • Need partial mocking of real objects
  • Want most methods to behave normally
  • Testing legacy code with limited refactoring options
  • Need to verify calls on real objects

Spy Gotchas

// WRONG - real method is called during stubbing
List<String> spy = spy(new ArrayList<>());
when(spy.get(0)).thenReturn("foo"); // IndexOutOfBoundsException!

// CORRECT - use doReturn family for spies
doReturn("foo").when(spy).get(0);

Mock Configuration Tips

// Good - descriptive names for debugging
UserService userService = mock(UserService.class, "userService");

// Good - appropriate default answers
HttpClient client = mock(HttpClient.class, RETURNS_SMART_NULLS);

// Good - extra interfaces when needed
Runnable task = mock(Runnable.class, 
    withSettings().extraInterfaces(Serializable.class));

Install with Tessl CLI

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

docs

annotations.md

argument-capturing.md

bdd-testing.md

index.md

junit-integration.md

matchers.md

mock-creation.md

stubbing.md

verification.md

tile.json