iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🥷

Stand-ins for Dependencies: Test Doubles or Mocks

に公開
2025/11/20

Introduction

A test double is a component that replaces a dependency of the system under test during testing. Mocks and stubs are types of test doubles.

The term "double" in test double originates from "stunt double"—a stand-in who performs dangerous stunts or action scenes in place of the primary actor.

The concept of organizing mocks, stubs, and similar ideas under the umbrella term "test double" was established by Gerard Meszaros in his 2007 book xUnit Test Patterns: Refactoring Test Code.

In this article, we will review the classical test doubles as categorized by Gerard Meszaros, and then examine whether and how these definitions are used in the real world, highlighting any differences.

This article assumes readers have experience writing automated tests in some programming language.

Classical Test Doubles

In the mid-2000s, Gerard Meszaros introduced the concept of test doubles in xUnit Test Patterns: Refactoring Test Code.

Tests typically execute the system under test by providing direct inputs (arguments or initial state). However, during actual execution, indirect inputs and indirect outputs also occur between the system under test and its dependent components.

Indirect Input/Output

Indirect Output
The effect that the system under test has on its dependent components or external environment during test execution, which cannot be directly observed through the system's public interface (return values or public state).

Indirect Input
Input that is not directly passed as arguments or initial state when the test calls the system under test, but is received by the system under test from dependent components or the external environment during execution.

The role of a "test double" is to control these indirect inputs and observe these indirect outputs.

When controlling indirect inputs, the dependent component is replaced during testing to supply values to the system under test that allow the test to continue.
Indirect Input

When observing indirect outputs, the dependent component is replaced during testing to record the indirect outputs made by the system under test, enabling verification in the test.
Indirect Output

Test doubles can be classified into the following types:

Class Diagram of Test Doubles

  • Dummy Object: An object that is passed as an argument to the system under test but is never actually used.
  • Test Stub: An object that replaces a dependent component, allowing the test to control indirect inputs.
  • Test Spy: An object that, in addition to the functionality of a Test Stub, records all indirect outputs.
  • Mock Object: An object that, in addition to the functionality of a Test Stub, verifies whether indirect outputs occurred as expected (by checking against pre-programmed expectations).
  • Fake Object: An object that replaces a dependent component with an alternative implementation that provides the same functionality.

Note that this classification in the book does not assume any specific test double library; rather, it serves as a design guideline for readers to implement and properly categorize test doubles themselves.
Consequently, as discussed later, there may be slight discrepancies with the concepts found in real-world test double libraries.

Dummy Object

A Dummy Object is an object that is passed as an argument to the system under test but is never actually used.

The following example demonstrates using a Dummy Object in Python for testing.
A DummyLogger is passed to satisfy a required argument, but the code under test does not expect DummyLogger to be used.

System Under Test

from abc import ABC, abstractmethod
class LoggerBase(ABC):
    @abstractmethod
    def info(self, msg: str):
        pass
    @abstractmethod
    def error(self, msg: str):
        pass

class FileLogger(LoggerBase):
    def info(self, msg: str):
        # ... implementation

    def error(self, msg: str):
        # ... implementation

class TargetService:
    def __init__(self, logger: LoggerBase) -> None:
        self._logger = logger
        self._cache = {}

    def get_cache(self, id: str) -> dict:
        # This method does not use logger at all
        return self._cache.get(id)

Test Code

class DummyLogger(LoggerBase):
    def info(self, msg: str):
        pass
    def error(self, msg: str):
        pass

def test_get_cache():
    dummy_logger = DummyLogger()
    service = TargetService(dummy_logger)

    service._cache = {"42": "data1"}
    act = service.get_cache("42")
    assert act == "data1"

Test Stub

An object that replaces a dependent component, allowing the test to control indirect inputs. Typically, indirect inputs are controlled through the return value of the test stub. Using a test stub makes it possible to execute paths in the system under test that would otherwise be difficult to reach.

The following is an example of controlling indirect inputs using a test stub with Python's pytest. In this example, the dependent component DatabaseClient is replaced with StubDatabaseClient, which returns data convenient for the test, thereby controlling indirect inputs.

Dependent Component example/external.py

class DatabaseClient:
    def fetch_user(self, user_id: str) -> dict:
        # Normally, this would access the database
        raise RuntimeError("real DB call!")

System Under Test example/service.py

from .external import DatabaseClient

def load_display_name(user_id: str) -> str:
    client = DatabaseClient()
    row = client.fetch_user(user_id)
    return row["display_name"]

Test Code

import pytest

from example import service
from example.external import DatabaseClient

# Test Stub: controls indirect inputs (DB return values) from the test side
class StubDatabaseClient(DatabaseClient):
    def __init__(self, fetch_user_result: dict) -> None:
        self._fetch_user_result = fetch_user_result

    def fetch_user(self, user_id: str) -> dict:
        # We ignore user_id for now and return a fixed value
        return self._fetch_user_result


def test_load_display_name(monkeypatch):
    # 1) Replace DatabaseClient with the Stub
    def _stub_ctor():
        # The `DatabaseClient()` call in the production code will come here
        return StubDatabaseClient({"id": "42", "display_name": "Taro Test"})

    # Replace the DatabaseClient referenced by the example.service module
    monkeypatch.setattr(service, "DatabaseClient", _stub_ctor)

    # 2) Execute the system under test
    act = service.load_display_name("42")

    # 3) Verify that the indirect input (display_name returned by the stub)
    #    is processed correctly
    assert act == "Taro Test"

This example was created to make Meszaros' definition easier to explain. For actual indirect input control, please consider a more sophisticated approach.

Stub

Even before Gerard Meszaros categorized test stubs, the term "stub" was already used in the context of software testing.
The word "stub" comes from Middle English "stubbe" (a tree stump), meaning a short remnant or incomplete leftover. In computer science, this evolved to refer to "a short placeholder for complete code" or "a temporary stand-in that cuts off real processing."
At least in the first edition of Glenford J. Myers' The Art of Software Testing published in 1979, the term "stub modules" was used to describe modules that simulate lower-level modules for testing higher-level ones, showing that stubs as substitutes for lower modules already existed.

Test Spy

A Test Spy is an object that functions as an observation point for indirect outputs. In addition to the functionality of a Test Stub, it records calls from the system under test to the dependent component, allowing the test to verify, during assertion, whether the dependent component was called as expected.

The following is an example of a Test Spy using Python's pytest. In this example, the dependent component MessageClient is replaced with SpyMessageClient, which records calls from send_user_info.

Dependent Component example/external.py

class MessageClient:
    def send_user(self, user_dict: dict) -> bool:
        raise RuntimeError("real Message call!")

System Under Test example/service.py

from .external import DatabaseClient, MessageClient

def send_user_info(user_id: str):
    db_client = DatabaseClient()
    msg_client = MessageClient()

    user_dict = db_client.fetch_user(user_id)
    return msg_client.send_user(user_dict)

Test Code

import pytest

from example import service
from example.external import DatabaseClient, MessageClient

class SpyMessageClient(MessageClient):
    def __init__(self) -> None:
        self.send_user_logs:list[dict] = []

    def send_user(self, user_dict: dict) -> bool:
        self.send_user_logs.append(user_dict)
        return True

def test_send_user_info_spy(monkeypatch):
    res_db_user = {"id": "42", "display_name": "Taro Test"}
    # 1) Replace DatabaseClient with a Stub
    def _stub_db_ctor():
        # The `DatabaseClient()` call in the production code will come here
        return StubDatabaseClient(res_db_user)
    # 2) Replace MessageClient with a Spy
    spy_msg_client = SpyMessageClient()
    def _spy_msg_ctor():
        # The `MessageClient()` call in the production code will come here
        return spy_msg_client
    monkeypatch.setattr(service, "DatabaseClient", _stub_db_ctor)
    monkeypatch.setattr(service, "MessageClient", _spy_msg_ctor)

    act = service.send_user_info("42")
    assert act, "send_user_info completed successfully"
    assert spy_msg_client.send_user_logs == [
        res_db_user
    ]

This example was created to make Meszaros' definition easier to explain. For actual observation of indirect outputs, please consider a more sophisticated approach.

Differences in Spy Nature

According to Gerard Meszaros' definition, a spy is "a stub that records data about the usage of a function." However, in practice, different schools of thought exist.
For example, in Mockito and Jest, a Spy is defined as "an object that records data about the usage of a function without interfering with its implementation."

Even Testing JavaScript Applications, which is aware of the test double concept, adopts the latter definition for spies, as shown below:

3.3 Test doubles: Mocks, stubs, and spies
Mocks, stubs, and spies are objects used to modify and replace parts of your application to ease or enable testing. As a whole, they're called test doubles.

  • Spies record data related to the usage of a function without interfering in its implementation.
  • Stubs record data associated with the usage of a function and change its behavior, either by providing an alternative implementation or return value.
  • Mocks change a function's behavior, but instead of just recording information about its usage, they have expectations preprogrammed.

Note that the default behavior of spies in Mockito and Jest is "record data about the usage of a function without interfering in its implementation," but you can also add the ability to change indirect inputs as a stub to that spy's behavior.

Mock Object

A Mock Object is an object that functions as an observation point for indirect outputs, similar to a Test Spy. However, a Mock Object differs from a Test Spy in that it uses assertions to compare the actual received calls against pre-defined expectations, causing the test to fail on behalf of the test method. As a result, the logic adopted to verify indirect outputs can be reused across all tests that use the same Mock Object.

The following is an example of a Mock Object using Python's pytest. In this example, the dependent component MessageClient is replaced with MockMessageClient, which verifies calls from send_user_info.

Test Code

class MockMessageClient(MessageClient):
    def __init__(self, expect_calls: list[dict]) -> None:
        self.expect_calls:list[dict] = expect_calls
        self.call_count = 0

    def send_user(self, user_dict: dict) -> bool:
        if self.call_count >= len(self.expect_calls):
            raise RuntimeError('Called more times than expected')
        assert self.expect_calls[self.call_count] == user_dict, "user_dict should be the expected argument"
        self.call_count += 1
        return True
    
    def verify(self):
        assert self.call_count == len(self.expect_calls), "Called the expected number of times"

def test_send_user_info_mock(monkeypatch):
    res_db_user = {"id": "42", "display_name": "Taro Test"}
    # 1) Replace DatabaseClient with a Stub
    def _stub_db_ctor():
        # The `DatabaseClient()` call in the production code will come here
        return StubDatabaseClient(res_db_user)
    # 2) Replace MessageClient with a Mock
    mock_msg_client = MockMessageClient([
        res_db_user
    ])
    def _mock_msg_ctor():
        return mock_msg_client
    monkeypatch.setattr(service, "DatabaseClient", _stub_db_ctor)
    monkeypatch.setattr(service, "MessageClient", _mock_msg_ctor)

    act = service.send_user_info("42")
    assert act, "send_user_info completed successfully"
    mock_msg_client.verify()

This example was created to make Meszaros' definition easier to explain. For actual verification of indirect outputs, please consider a more sophisticated approach.

Mock Objects are basically divided into two types:

  • Strict Mock Objects: The test fails if correct calls are received in a different order than specified.
  • Lenient Mock Objects: They allow calls out of order. Some lenient mock objects allow or ignore unexpected or failed calls.

The example above is a strict mock object.

History of Mock Objects

The concept of mock objects existed even before Gerard Meszaros categorized them.

According to Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce, the history of mock objects dates back to around late 1999.
Mock objects were invented by the people at Connextra, who were developing a contextual advertising system for the web.

Tim Mackinnon and others presented their results in 2001 in Endo-Testing: Unit Testing with Mock Objects.

In this paper, mock objects are described as follows:

We propose a technique called Mock Objects in which we replace domain code with dummy implementations that both emulate real functionality and enforce assertions about the behaviour of our code. These Mock Objects are passed to the target domain code which they test from inside, hence the term Endo-Testing. Unlike conventional techniques, however, assertions are not left in production code, but gathered together in unit tests.

A few years after this paper, Tim Mackinnon and others published Mock Roles, not Objects. Here, they demonstrate a style where mocks are not just "test aids" but tools for guiding object responsibility division and interface design, by writing expected messages (roles) in tests and evolving the implementation accordingly.

Fake Object

A Fake Object is a "working alternative implementation" of a dependent component, unlike Test Stubs or Mock Objects which aim to control or verify indirect inputs/outputs. It is a test double used to provide a simpler, faster "alternative mini-implementation" that has the same interface as the real component, utilized during testing.

Common examples include replacing database access with a simpler in-memory database, or using LocalStack instead of making actual AWS calls.

Stubs, Spies, and Mocks in the Real World

In the classical test double definitions presented by Gerard Meszaros, stubs, spies, and mocks were clearly categorized. However, in the real world, it cannot be said that we software engineers implement unit tests with these definitions in mind. Furthermore, the test double libraries we use do not strictly separate stubs, spies, and mocks, nor do they provide functionality exactly conforming to the classical test double definitions.

A 2020 paper, Assessing Mock Classes: An Empirical Study, which surveyed the usage of test doubles, notes that the terms "mock object" and "test double" are often used synonymously.

Today, when the word "mock" is used, what it refers to depends on the context. In some situations, it implies a stub that verifies pre-defined expected behavior, following Meszaros' definition. In other situations, it may refer to a "partial mock" that replaces only some methods of a real object. In yet other cases, it might refer to something like a test spy that does not define expected behavior in advance but verifies it afterward. And sometimes, it is used to mean the entire concept of a test double that replaces dependent components.

The same applies not only to "mock" but also to the word "spy." According to Gerard Meszaros' definition, a spy is a stub that records usage. However, today, a "partial mock that can record usage" is sometimes called a "spy."

Here, we will examine specific test double libraries individually to see how they use and refer to stubs, spies, and mocks.

Test Doubles for Java

A characteristic of test doubles for Java is that replacing dependencies tends to favor Dependency Injection.

For example, a class under test typically defines interfaces for its dependent components and allows the actual implementations to be swapped out by some means.

Example of Java code under test

Interface of a dependent component

public interface DatabaseClient {
    Map<String, String> fetchUser(String userId);
}
public interface MessageClient {
    boolean sendUser(Map<String, String> userDict);
}

Actual implementation of a dependent component

public class RealDatabaseClient implements DatabaseClient {
    @Override
    public Map<String, String> fetchUser(String userId) {
        // Normally, this would be a DB access
        throw new RuntimeException("real DB call!");
    }
}
public class RealMessageClient implements MessageClient {
    public String getVersion() {
        return "ver0.1";
    }
    @Override
    public boolean sendUser(Map<String, String> userDict) {
        // Normally, this would be an external service call
        throw new RuntimeException("real message call!");
    }
}

Code under test

public class UserService {

    private final DatabaseClient databaseClient;
    private final MessageClient messageClient;

    public UserService(DatabaseClient databaseClient, MessageClient messageClient) {
        this.databaseClient = databaseClient;
        this.messageClient = messageClient;
    }

    public boolean sendUserInfo(String userId) {
        Map<String, String> userDict = databaseClient.fetchUser(userId);
        return messageClient.sendUser(userDict);
    }
}

However, in cases such as dealing with legacy code where the code under test cannot be modified, some libraries provide ways to replace dependencies without dependency injection by modifying bytecode.

EasyMock

EasyMock is a test double library for Java that has existed since around 2001. Version 5.6.0 was released in 2025.

Its behavior is close to the mock objects envisioned by Gerard Meszaros.

The test procedure using EasyMock is as follows:

  1. Create a mock.
  2. Set the mock on the class under test (dependency injection).
  3. Record "how the mock should behave."
  4. Inform all mocks that the actual test is about to be executed.
  5. Run the test.
  6. Verify that all expected calls were made (verify).

A concrete example of testing with DatabaseClient and MessageClient interfaces replaced by mock objects is shown below.

    @Test
    void test_sendUserInfo_with_mocks() {
        // arrange
        DatabaseClient dbMock = createMock(DatabaseClient.class);
        MessageClient msgMock = createMock(MessageClient.class);

        Map<String, String> dbUser = Map.of(
                "id", "42",
                "display_name", "Test Taro"
        );

        expect(dbMock.fetchUser("42")).andReturn(dbUser);
        expect(msgMock.sendUser(dbUser)).andReturn(true);

        replay(dbMock, msgMock);

        UserService sut = new UserService(dbMock, msgMock);

        // act
        boolean act = sut.sendUserInfo("42");

        // assert
        assertTrue(act);

        // If called as expected, verify() passes (including the call count)
        verify(dbMock, msgMock);
    }

Originally, EasyMock could only create mock objects for interfaces, but the current version also allows mocking classes.

        RealDatabaseClient dbMock = createMock(RealDatabaseClient.class);
        RealMessageClient msgMock = createMock(RealMessageClient.class);

EasyMock does not have a dedicated stub feature. Using Nice Mocks allows it to play a stub-like role by controlling only indirect inputs without verifying the strictness of calls.

        // ★ DatabaseClient is treated as a "stub": only define return values, ignore call count
        DatabaseClient dbStub = createNiceMock(DatabaseClient.class);
        // ...
        // Promise to "return this data when '42' is passed" but relax the call count constraint
        expect(dbStub.fetchUser("42"))
                .andReturn(dbUser)
                .anyTimes();   // ← Stub-like: allow any number of calls
        // ...
        verify(msgMock);

partialMockBuilder enables partial mocks. In the following example, sendUser returns the mock object's result, but other methods like getVersion() execute the real method and return its result.

        // ★ Use partialMockBuilder as recommended by the User Guide
        RealMessageClient msgPartialMock = partialMockBuilder(RealMessageClient.class)
                .addMockedMethod("sendUser")  // Only this method is mocked
                .createMock();

        expect(msgPartialMock.sendUser(dbUser)).andReturn(true);

EasyMock does not provide a test spy-like feature that lets you run the code first and verify calls later.

EasyMock has limitations on which methods can be replaced. For example, private methods cannot be replaced.
One way to bypass this limitation is to use PowerMock as an add-on. However, no release of PowerMock has been made since 2020, and the author himself has stated that he does not have time to maintain PowerMock, so careful consideration is needed regarding whether it remains a viable option.

JMock2

jMock2 is a test double library that has existed since around 2007. Version 2.13.1 was released in 2024.

The existence of jMock itself can be confirmed in the paper Mock Roles, not Objects by Tim Mackinnon et al. One of the most famous books that confirms the existence of jMock2 is Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce.

By default, JMock2 can only create mock objects for interfaces.

package example.service;

import example.external.DatabaseClient;
import example.external.MessageClient;
import org.jmock.Expectations;
import org.jmock.junit5.JUnit5Mockery;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserServiceJMockTest {

    // Integrating jMock with JUnit 5: using @RegisterExtension + JUnit5Mockery
    @RegisterExtension
    JUnit5Mockery context = new JUnit5Mockery();

    @Test
    void test_sendUserInfo_with_jmock() {
        // --- Create mocks ---
        DatabaseClient db = context.mock(DatabaseClient.class);
        MessageClient msg = context.mock(MessageClient.class);

        Map<String, String> dbUser = Map.of(
                "id", "42",
                "display_name", "Test Taro"
        );

        // --- Define expectations (jMock DSL) ---
        context.checking(new Expectations() {{
            // DatabaseClient.fetchUser("42") is called once and returns dbUser
            oneOf(db).fetchUser("42");
            will(returnValue(dbUser));

            // MessageClient.sendUser(dbUser) is called once and returns true
            oneOf(msg).sendUser(dbUser);
            will(returnValue(true));
        }});

        UserService sut = new UserService(db, msg);

        // --- act ---
        boolean act = sut.sendUserInfo("42");

        // --- assert ---
        assertTrue(act);

        // The JUnit5Mockery verifies automatically at the end of the test that expectations were met.
        // If you want to do it explicitly:
        context.assertIsSatisfied();
    }
}

jMock2 does not have a dedicated stub feature, but using allowing or atLeast(0) allows creating mock objects that behave like stubs.

        // --- Define expectations (jMock DSL) ---
        context.checking(new Expectations() {{
            // DatabaseClient.fetchUser("42") may be called zero or more times.
            // If called, return dbUser
            allowing(db).fetchUser("42");
            will(returnValue(dbUser));
        }});
        // --- Define expectations (jMock DSL) ---
        context.checking(new Expectations() {{
            // DatabaseClient.fetchUser("42") is called at least 0 times and returns dbUser
            atLeast(0).of(db).fetchUser("42");
            will(returnValue(dbUser));
        }});

No spy or partial mock functionality could be found for JMock2.

The jmock-imposters add-on can create mock objects for concrete classes.

package example.service;
import example.external.RealDatabaseClient;
import example.external.RealMessageClient;
import org.jmock.Expectations;
import org.jmock.junit5.JUnit5Mockery;
import org.jmock.imposters.ByteBuddyClassImposteriser;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.RegisterExtension;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertTrue;

class UserServiceJMockTestRealClass {

    // Integrating jMock with JUnit 5: using @RegisterExtension + JUnit5Mockery
    @RegisterExtension
    JUnit5Mockery context = new JUnit5Mockery() {{
        // Enable mocking of classes
        setImposteriser(ByteBuddyClassImposteriser.INSTANCE);
    }};


    @Test
    void test_sendUserInfo_with_jmock() {
        // --- Create mocks ---
        RealDatabaseClient db = context.mock(RealDatabaseClient.class);
        RealMessageClient msg = context.mock(RealMessageClient.class);

        Map<String, String> dbUser = Map.of(
                "id", "42",
                "display_name", "Test Taro"
        );

        // --- Define expectations (jMock DSL) ---
        context.checking(new Expectations() {{
            // DatabaseClient.fetchUser("42") is called once and returns dbUser
            oneOf(db).fetchUser("42");
            will(returnValue(dbUser));

            // MessageClient.sendUser(dbUser) is called once and returns true
            oneOf(msg).sendUser(dbUser);
            will(returnValue(true));
        }});

        UserService sut = new UserService(db, msg);

        // --- act ---
        boolean act = sut.sendUserInfo("42");

        // --- assert ---
        assertTrue(act);

        // The JUnit5Mockery verifies automatically at the end of the test that expectations were met.
        // If you want to do it explicitly:
        context.assertIsSatisfied();
    }
}

References:

Mockito

Mockito is a test double framework that first appeared in early 2008, releasing v5.20.0 in 2025. Mockito started as an improvement upon EasyMock by refining existing ideas. Unlike existing mock object tools such as EasyMock, it aims for simplicity by eliminating the need to write verification-related code before test execution.

Despite its name, Mockito is closer to being a Test Spy framework. In fact, the author of Mockito has said that "Mockito mock" should have been called "Test Spy."

Below is a sample of interface mocking using Mockito.

package example.service;

import example.external.RealDatabaseClient;
import example.external.RealMessageClient;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.anyMap;
import static org.mockito.Mockito.*;

class UserServiceMockitoStyleTest {
    @Test
    void test_sendUserInfo_with_if_mocks() {
        // arrange
        DatabaseClient dbMock = mock(DatabaseClient.class);
        MessageClient msgMock = mock(MessageClient.class);

        Map<String, String> dbUser = Map.of(
                "id", "42",
                "display_name", "Test Taro"
        );

        when(dbMock.fetchUser("42")).thenReturn(dbUser);
        when(msgMock.sendUser(dbUser)).thenReturn(true);

        UserService sut = new UserService(dbMock, msgMock);

        // act
        boolean act = sut.sendUserInfo("42");

        // assert
        assertTrue(act);
        // Mockito-style mock: verify "how many times and with what arguments it was called"
        verify(dbMock, times(1)).fetchUser("42");
        verify(msgMock, times(1)).sendUser(dbUser);
        verifyNoMoreInteractions(dbMock, msgMock);
    }
}

Compared to EasyMock, the setup before test execution is simpler. Mockito can also create mock objects for classes.

        RealDatabaseClient dbMock = mock(RealDatabaseClient.class);
        RealMessageClient msgMock = mock(RealMessageClient.class);

Mockito does not have a dedicated class or method called "stub," but mock can serve a stub role, offering a simpler setup than EasyMock or JMock2.

Mockito also provides a feature called spy. Its functionality is as follows:

  • Wraps a real class
    • Can be used as a partial mock by replacing only specific methods
    • Can verify the invocation while actually calling the real method

For more details on how to use Mockito's spy, see the example below.

    @Test
    void test_sendUserInfo_with_spy1() {
        // Create a partial mock with Mockito's spy(...)
        RealMessageClient realRealMessageClient = new RealMessageClient();
        RealMessageClient spyMsg = spy(realRealMessageClient);
        // If nothing is set up, the real method is called
        assertEquals(spyMsg.getVersion(), "ver0.1");
        verify(spyMsg, times(1)).getVersion();

        // Stub only a specific method (partial mock)
        doReturn("xxxx").when(spyMsg).getVersion();
        assertEquals(spyMsg.getVersion(), "xxxx");
        verify(spyMsg, times(2)).getVersion();
    }

As seen above, Mockito's definition of "spy" deviates from Gerard Meszaros' definition. According to Meszaros, a spy is a stub that records usage. However, Mockito uses the name "spy" for a feature that provides a "partial mock that records usage." This discrepancy is acknowledged but is not planned to be corrected.

Mockito also supports mocking without dependency injection by using mockConstruction, allowing the replacement of dependent classes such as DatabaseClient and MessageClient directly within the code under test.

Example of code under test

public class UserServiceNoDI {
    public boolean sendUserInfo(String userId) {
        RealDatabaseClient databaseClient = new RealDatabaseClient();
        RealMessageClient messageClient = new RealMessageClient();

        Map<String, String> userDict = databaseClient.fetchUser(userId);
        return messageClient.sendUser(userDict);
    }
}

Test code

package example.service;

import example.external.DatabaseClient;
import example.external.MessageClient;
import org.junit.jupiter.api.Test;
import org.mockito.MockedConstruction;

import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.*;

/**
 * Testing UserService without DI (which creates instances internally with new).
 * Uses Mockito's mockConstruction(...) to mock constructors.
 */
class UserServiceNoDiMockitoTest {
    /**
     * Test for sendUserInfo().
     * - Hooks both new DatabaseClient() and new MessageClient() with mockConstruction
     * - Stubs the return value of DatabaseClient#fetchUser
     * - Verifies the arguments and invocation count of MessageClient#sendUser
     */
    @Test
    void test_sendUserInfo_with_constructor_mocks() {
        Map<String, String> dbUser = Map.of(
                "id", "42",
                "display_name", "Test Taro"
        );

        // Mock the constructor of RealDatabaseClient
        try (MockedConstruction<RealDatabaseClient> dbConstr = mockConstruction(
                     RealDatabaseClient.class,
                     (mock, context) -> when(mock.fetchUser("42")).thenReturn(dbUser)
             );
             // Also mock the constructor of RealMessageClient
             MockedConstruction<RealMessageClient> msgConstr = mockConstruction(
                     RealMessageClient.class,
                     (mock, context) -> when(mock.sendUser(dbUser)).thenReturn(true)
             )) {

            UserServiceNoDI sut = new UserServiceNoDI();

            boolean act = sut.sendUserInfo("42");

            assertTrue(act, "sendUserInfo should complete successfully");

            // Verify that new RealDatabaseClient() and new RealMessageClient() were each called once
            assertEquals(1, dbConstr.constructed().size(), "RealDatabaseClient must be new'd exactly once");
            assertEquals(1, msgConstr.constructed().size(), "RealMessageClient must be new'd exactly once");

            RealDatabaseClient dbMock = dbConstr.constructed().get(0);
            RealMessageClient msgMock = msgConstr.constructed().get(0);

            // Verify as in typical Mockito style
            verify(dbMock, times(1)).fetchUser("42");
            verify(msgMock, times(1)).sendUser(dbUser);
            verifyNoMoreInteractions(dbMock, msgMock);
        }
    }
}

References:

Test Doubles for C# (.NET)

C# is a language with characteristics very similar to Java, so it tends to be difficult to use test doubles without dependency injection.

Example of C# code under test

Interface for dependent component

// Example/External/IDatabaseClient.cs
using System.Collections.Generic;

namespace Example.External
{
    public interface IDatabaseClient
    {
        Dictionary<string, string> FetchUser(string userId);
    }
}
// Example/External/IMessageClient.cs
using System.Collections.Generic;

namespace Example.External
{
    public interface IMessageClient
    {
        bool SendUser(Dictionary<string, string> userDict);
    }
}
// Example/External/RealDatabaseClient.cs
using System;
using System.Collections.Generic;

namespace Example.External
{
    // Originally an implementation that connects to the DB, but here it's NotImplemented as an example
    public class RealDatabaseClient : IDatabaseClient
    {
        public virtual Dictionary<string, string> FetchUser(string userId)
        {
            throw new NotImplementedException("Real DB access is not implemented.");
        }
    }
}
// Example/External/RealMessageClient.cs
using System;
using System.Collections.Generic;

namespace Example.External
{
    public class RealMessageClient : IMessageClient
    {
        // Implementation that throws an exception unless mocked
        public virtual bool SendUser(Dictionary<string, string> userDict)
        {
            throw new NotImplementedException("Real message sending is not implemented.");
        }

        // Corresponds to getVersion() verified on the EasyMock side
        public virtual string GetVersion() {
          return "ver0.1";
        }
    }
}

Code under test

// Example/Service/UserService.cs
using System.Collections.Generic;
using Example.External;

namespace Example.Service
{
    public class UserService
    {
        private readonly IDatabaseClient _databaseClient;
        private readonly IMessageClient _messageClient;

        public UserService(IDatabaseClient databaseClient, IMessageClient messageClient)
        {
            _databaseClient = databaseClient;
            _messageClient = messageClient;
        }

        public string LoadDisplayName(string userId)
        {
            Dictionary<string, string> row = _databaseClient.FetchUser(userId);
            return row["display_name"];
        }

        public bool SendUserInfo(string userId)
        {
            Dictionary<string, string> userDict = _databaseClient.FetchUser(userId);
            return _messageClient.SendUser(userDict);
        }
    }
}

Moq

Moq is a .NET mocking library that has existed since the late 2000s. Version 4.20.72 was released in 2024.

It imposes strict restrictions on replaceable classes. Any interface type can be used for mocking, but for classes, only abstract and virtual members can be mocked. Additionally, there is no feature to replace dependent components with test doubles without dependency injection.

An example test using Moq is shown below.

using System.Collections.Generic;
using Example.External;
using Example.Service;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;

namespace Example.Tests.Service
{
    [TestClass]
    public class UserServiceMoqStyleTests
    {
        [TestMethod]
        public void SendUserInfo_with_if_mocks()
        {
            // arrange
            var dbMock = new Mock<IDatabaseClient>(MockBehavior.Strict);
            var msgMock = new Mock<IMessageClient>(MockBehavior.Strict);

            var dbUser = new Dictionary<string, string>
            {
                ["id"] = "42",
                ["display_name"] = "Test Taro",
            };

            dbMock
                .Setup(x => x.FetchUser("42"))
                .Returns(dbUser)
                .Verifiable();

            msgMock
                .Setup(x => x.SendUser(dbUser))
                .Returns(true)
                .Verifiable();

            var sut = new UserService(dbMock.Object, msgMock.Object);

            // act
            bool act = sut.SendUserInfo("42");

            // assert
            Assert.IsTrue(act);
            dbMock.Verify();
            msgMock.Verify();
        }
    }
}

The above example is the so-called mock object as conceived by Gerard Meszaros—a stub that verifies pre-defined expected behavior. Regardless of MockBehavior.Strict/Loose, Moq's Mock records invocations in the Invocations property. However, in Strict mode, unset calls throw an exception, so using Loose is easier for a Spy-like usage where you "let it be called first and then read Invocations later." Here, Loose is used for that purpose.

        [TestMethod]
        public void SendUserInfo_with_spy_like_message_client()
        {
            // arrange
            var dbStub = new Mock<IDatabaseClient>();
            var dbUser = new Dictionary<string, string>
            {
                ["id"] = "42",
                ["display_name"] = "Test Taro",
            };

            dbStub
                .Setup(x => x.FetchUser("42"))
                .Returns(dbUser);

            var msgMock = new Mock<IMessageClient>(); // MockBehavior.Loose

            // Only stub the return value (this is the "stub part" from a Spy perspective)
            msgMock
                .Setup(m => m.SendUser(It.IsAny<Dictionary<string, string>>()))
                .Returns(true);

            var sut = new UserService(dbStub.Object, msgMock.Object);

            // act
            bool act = sut.SendUserInfo("42");

            // assert
            Assert.IsTrue(act);

            // "Spy-style post-verification" part
            var sendUserInvocations = msgMock.Invocations
                .Where(inv => inv.Method.Name == nameof(IMessageClient.SendUser))
                .ToList();

            // Verify call count
            Assert.AreEqual(1, sendUserInvocations.Count, "SendUser must be called exactly once");

            // Verify arguments
            var firstCall = sendUserInvocations[0];
            var arg0 = (Dictionary<string, string>)firstCall.Arguments[0];

            // Verify that the same Dictionary was passed (reference equality)
            Assert.AreSame(dbUser, arg0);
            Assert.AreEqual("42", arg0["id"]);
            Assert.AreEqual("Test Taro", arg0["display_name"]);
        }

Partial mocking is possible using CallBase=True.

            // Partial mock of RealMessageClient
            var msgPartialMock = new Mock<RealMessageClient>(MockBehavior.Loose)
            {
                // When true, methods that are not Set up will call the base class implementation
                CallBase = true
            };
            // Only mock sendUser (equivalent to EasyMock's addMockedMethod("sendUser"))
            msgPartialMock
                .Setup(m => m.SendUser(dbUser))
                .Returns(true)
                .Verifiable();

            // Omitted...
            // Since CallBase = true, GetVersion calls the real implementation
            Assert.AreEqual("ver0.1", msgPartialMock.Object.GetVersion());

Even using Invocations and CallBase, it is possible to achieve the spy and partial mock as conceived by Gerard Meszaros, but there is no mechanism to record calls to the real function like Mockito's spy.

Moq's design philosophy, as stated in its README, is that you can use it without being aware of the differences between mocks, stubs, and fakes.

References

Microsoft Fakes

Microsoft Fakes is a powerful way to replace .NET dependent components with test doubles. It provides two approaches: Stub and Shim.

  • Stub: Replaces interfaces or virtual methods with a test "replacement class."
  • Shim: Intercepts calls to compiled code (static/non-virtual, etc.) at runtime and replaces them with alternative processing.

The Shim feature is particularly powerful, allowing any method to be replaced with a test double without dependency injection, making it a valuable tool for legacy environments. However, Microsoft Fakes provides only the replacement mechanism; it does not offer mocking or spying functionality—you need to handle that yourself.

For details on how Microsoft Fakes works, refer to the following:

Microsoft Fakes is a powerful tool for achieving test doubles, but it is only available in Visual Studio Enterprise. Several similar open-source projects exist, but their update frequency may be a concern.

If you are considering an open-source alternative to Microsoft Fakes at this point, consider adopting poser, the successor of pose.

I have written a brief explanation below.
https://zenn.dev/mima_ita/articles/463bb8e5c8b9f1

Test Doubles for Python

Due to the characteristics of the Python language, it is relatively easy to replace dependencies with test doubles without dependency injection. For example, checking pytest's monkeypatch, you can see that it replaces functions with a simple implementation.

Code under test

Dependent object example/external.py

class DatabaseClient:
    def fetch_user(self, user_id: str) -> dict:
        # Originally DB access
        raise RuntimeError("real DB call!")

class MessageClient:
    def send_user(self, user_dict: dict) -> bool:
        raise RuntimeError("real DB call!")
    def get_version(self):
        return "v1.0"

Code under test example/service.py

from .external import DatabaseClient, MessageClient


def send_user_info(user_id: str):
    db_client = DatabaseClient()
    msg_client = MessageClient()

    user_dict = db_client.fetch_user(user_id)
    return msg_client.send_user(user_dict)

def send_user_info_di(user_id: str, db_client, msg_client):
    user_dict = db_client.fetch_user(user_id)
    return msg_client.send_user(user_dict)

unittest.mock

unittest.mock is a test double library included in the Python standard library. It was originally a third-party library called mock created by Michael Foord, which was incorporated into the standard library starting from Python 3.3. Unlike the

EasyMockのような期待する振る舞いを登録してからテストを実行するという動きではなく、テストを実行し呼ばれ方を検証するという設計思想になっています。(mockitoの思想に近しい)

次のような依存を注入する関数をテストする場合はMockクラスを使用します。

テストコード

def test_send_user_info_di():
    res_db_user = {"id": "42", "display_name": "テスト太郎"}
    mock_db = Mock(spec=DatabaseClient)
    mock_msg = Mock(spec=MessageClient)

    mock_db.fetch_user.return_value = res_db_user
    mock_msg.send_user.return_value = res_db_user

    act = service.send_user_info_di("42", mock_db, mock_msg)
    assert act, "send_user_infoが正しく完了したこと"

    mock_db.fetch_user.assert_called_once_with("42")
    mock_msg.send_user.assert_called_once_with(res_db_user)

依存を注入しない関数をテストする場合は、patchを使用します。
with patch.object(...): の コンテキストのスコープ内に限り、元の実装ではなく、テストダブルに差し変わります。

テストコード

def test_send_user_info_mock_instance():
    res_db_user = {"id": "42", "display_name": "テスト太郎"}

    with patch("example.service.DatabaseClient") as MockDatabaseClient, \
        patch("example.service.MessageClient") as MockMessageClient:
        mock_db = MockDatabaseClient.return_value
        mock_db.fetch_user.return_value = res_db_user
        mock_msg = MockMessageClient.return_value
        mock_msg.send_user.return_value = True

        act = service.send_user_info("42")

        assert act, "send_user_infoが正しく完了したこと"

        # 「モック」として send_user が期待通り 1回だけ呼ばれたことを厳密に検証
        mock_msg.send_user.assert_called_once_with(res_db_user)

部分モックの方法はいくつかあります。
Mock(wraps=元オブジェクト,)を使用する方法ではMockのwraps引数に元になるオブジェクトを指定します。

def test_like_partial_mock1():
    res_db_user = {"id": "42", "display_name": "テスト太郎"}
    mock_db = Mock(spec=DatabaseClient)
    real_msg = MessageClient()
    mock_msg = Mock(wraps=real_msg, spec=MessageClient)

    mock_db.fetch_user.return_value = res_db_user
    mock_msg.send_user.return_value = res_db_user

    act = service.send_user_info_di("42", mock_db, mock_msg)
    assert act, "send_user_infoが正しく完了したこと"

    mock_db.fetch_user.assert_called_once_with("42")
    mock_msg.send_user.assert_called_once_with(res_db_user)
    print(mock_msg.get_version()) # 元関数が呼ばれる
    print(mock_msg.get_version.call_count) # 1

patch使用時に置き換えたいメソッドだけを指定することでも、部分モックができます。

def test_send_user_info_mock_mock_lib():
    res_db_user = {"id": "42", "display_name": "テスト太郎"}

    with patch.object(
            DatabaseClient, "fetch_user",
            return_value=res_db_user
        ), \
        patch.object(
            MessageClient, "send_user",
            return_value=True
        ) as mock_send_user:
        # テスト対象を実行
        act = service.send_user_info("42")

        assert act, "send_user_infoが正しく完了したこと"

        # 「モック」として send_user が期待通り 1回だけ呼ばれたことを厳密に検証
        mock_send_user.assert_called_once_with(res_db_user)
        print(MessageClient().get_version())

部分モックした場合、戻り値をしていない他のメソッドは本物の関数を呼び出せるが、call_countなどの呼び出し方法の記録も行われています。
この挙動はmockitoのspyに類似しています。

参考

JavaScriptを対象としたテストダブル

JavaScriptの場合、その言語特性からか、依存の注入なしでテストダブルに置き換えることが容易になっています。

以下のページにあるように、JavaScriptのテストにおけるテストダブル の概念全体が「モック」としてあつかわれる傾向が多いです。
[AskJS] Can we talk about Stubs, Spies and Mocks in JavaScript and what a mess they are?

テスト対象

依存コンポーネント src/external.js

class DatabaseClient {
  fetchUser(userId) {
    // 本来は DB アクセス
    throw new Error("real DB call!");
  }
}

class MessageClient {
  sendUser(userDict) {
    console.log("本物", userDict);
  }
  getVersion() {
    return "v0.1";
  }
}

module.exports = {
  DatabaseClient,
  MessageClient,
};

テスト対象 src/service.js

const { DatabaseClient, MessageClient } = require("./external");

function sendUserInfo(userId) {
  const dbClient = new DatabaseClient();
  const msgClient = new MessageClient();
  const userDict = dbClient.fetchUser(userId);
  return msgClient.sendUser(userDict);
}

function sendUserInfoDi(userId, dbClient, msgClient) {
  const userDict = dbClient.fetchUser(userId);
  return msgClient.sendUser(userDict);
}

module.exports = {
  sendUserInfo,
  sendUserInfoDi
};

SinonJS

SinonJSは2010年頃から公開されているテストダブルのライブラリです。

stub機能は間接入力を制御する機能とともに、使用状況を記録します。
Gerard Meszarosの想定するテストスパイに該当します。

const external = require("../src/external");
const service = require("../src/service");
const sinon = require('sinon')

afterEach(() => {
  sinon.restore();
});


test("スタブの例ー依存関係注入", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };
  const dbStub = {
    fetchUser: sinon.stub().returns(resDbUser),
  };
  const msgStub = {
    sendUser: sinon.stub().returns(true)
  };
  const act = service.sendUserInfoDi("42", dbStub, msgStub);

  expect(act).toBe(true);

  // 「どう呼ばれたか」を検証(Spyのような役割)
  expect(dbStub.fetchUser.callCount).toBe(1);
  expect(dbStub.fetchUser.calledWith("42")).toBeTruthy();
  expect(msgStub.sendUser.callCount).toBe(1);
  expect(msgStub.sendUser.calledWith(resDbUser)).toBeTruthy();
});

spyは本物の関数に対する使用状況を記録するための機能です。

test("spyの例", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };
  const msgObj = new external.MessageClient()
  const msgSendUserSpy = sinon.spy(msgObj, "sendUser");
  const dbStub = {
    fetchUser: sinon.stub().returns(resDbUser),
  };
  const act = service.sendUserInfoDi("42", dbStub, msgObj);

  // 「どう呼ばれたか」を検証(Spyのような役割)
  expect(dbStub.fetchUser.callCount).toBe(1);
  expect(dbStub.fetchUser.calledWith("42")).toBeTruthy();
  expect(msgSendUserSpy.callCount).toBe(1);
  expect(msgSendUserSpy.calledWith(resDbUser)).toBeTruthy();

});

mockは事前に期待する振る舞いを定義する必要のあるGerard Meszarosの想定するモックオブジェクトになっています。

test("モックの例", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };
  const msgObj = new external.MessageClient()
  const msgMock = sinon.mock(msgObj);
  msgMock
      .expects("sendUser")
      .once()
      .withArgs(resDbUser)
      .returns(true);
  const dbStub = {
    fetchUser: sinon.stub().returns(resDbUser),
  };
  const act = service.sendUserInfoDi("42", dbStub, msgObj);

  expect(act).toBe(true);

  // 「どう呼ばれたか」を検証(Spyのような役割)
  expect(dbStub.fetchUser.callCount).toBe(1);
  expect(dbStub.fetchUser.calledWith("42")).toBeTruthy();
  msgMock.verify();

});

fakeは共通のテストダブルを作り、あとからそれを差し替えるための機能です。これはGerard Meszarosの考えるフェイクオブジェクトとは異なる概念になります。

SinonJSでのfakeの例は、以下のようにloggerのinfo, warn, errorに同じfakeに置き換えるような使いかたが考えられます。

const logFake = sinon.fake();  // 呼び出し履歴だけ欲しい

sinon.replace(logger, "info", logFake);
sinon.replace(logger, "warn", logFake);
sinon.replace(logger, "error", logFake);

// どのレベル経由で呼ばれたかも fake.getCalls() から分かる

Jest

JestはFacebookが2011年から開発したテストフレームワークです。2014年にオープンソース化され、2022年にはOpenJS Foundationに移管されています。2025年にはv30.0がリリースされています。

Jestはテストダブルの機能をサポートしており、その設計思想はmockitoやunittest.mockに近いものがあり、モックオブジェクトに対して事前の期待する振る舞いの設定を不要としています。
Testing JavaScript ApplicationsではJestのテストダブルの機能について3.3 Test doubles: Mocks, stubs, and spiesで以下のように言及しています。

NOTE Engineers often conflate the terms mocks, stubs, and spies, even though, formally, these terms have different definitions.
Especially in the context of Jest, you will frequently see people referring to stubs and spies as mocks. This confusion happens because Jest's API and documentation tends to use the name mock for every kind of test double.
Ironically, if we adhere to the most accepted definition of a mock, it's the only kind of test double that Jest does not include.
Note: エンジニアは、形式的にはそれぞれ異なる定義を持つ用語であるにもかかわらず、モック、スタブ、スパイという用語を混同して使ってしまうことがよくあります。
特に Jest の文脈では、スタブやスパイを「モック」と呼んでいるのを頻繁に目にします。
この混乱が起きるのは、Jest の API やドキュメントが、あらゆる種類のテストダブルに対して mock という名前を使う傾向があるからです。
皮肉なことに、もし最も広く受け入れられている「モック」の定義に従うなら、Jest に含まれていない唯一のテストダブルこそが、そのモックなのです。

Jestがあらゆる種類のテストダブルに対してモックを使う事例はMock Functionsで確認できます。

Mock functions are also known as "spies", because they let you spy on the behavior of a function that is called indirectly by some other code, rather than only testing the output.
モック関数は「スパイ(spy)」とも呼ばれます。なぜなら、単に出力だけをテストするのではなく、ほかのコードから間接的に呼び出される関数の振る舞いを「監視(スパイ)」できるからです。

このことから、Jestの世界では「モック」は依存コンポーネントを置き換える「テストダブル」全体を指す意味で使われていることがわかります。

jest.fn()で作成したオブジェクトは、呼び出しの記録とスタブのような役割をするいわゆるテストスパイとして使用できます。

const { DatabaseClient, MessageClient } = require("../src/external");
const service = require("../src/service");

afterEach(() => {
  jest.restoreAllMocks(); // spyOn を元に戻す
});
test("作成したオブジェクトを渡す", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };
  const mockDb = {
    fetchUser: jest.fn().mockReturnValue(resDbUser),
  };
  const mockMsg = {
    sendUser: jest.fn().mockReturnValue(true),
  };
  const act = service.sendUserInfoDi("42", mockDb, mockMsg);
  expect(act).toBe(true);

  // 「どう呼ばれたか」を検証(Spy)
  expect(mockDb.fetchUser).toHaveBeenCalledTimes(1);
  expect(mockDb.fetchUser).toHaveBeenCalledWith("42");

  expect(mockMsg.sendUser).toHaveBeenCalledTimes(1);
  expect(mockMsg.sendUser).toHaveBeenCalledWith(resDbUser);
});

依存の注入が行えないテスト対象は、以下の方法があります。

  • prototype中のメソッドをspyOnで差し替える
  • jest.mockを使用してクラス自体をjest.fnとする

prototypeの置き換え例

test("spyOnでの部分的な差し替え", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };

  const fetchUserSpy = jest
    .spyOn(DatabaseClient.prototype, "fetchUser")
    .mockReturnValue(resDbUser);

  const sendUserSpy = jest
    .spyOn(MessageClient.prototype, "sendUser")
    .mockReturnValue(true);

  const act = service.sendUserInfo("42");

  expect(act).toBe(true);

  // 「どう呼ばれたか」を検証(Spy)
  expect(fetchUserSpy).toHaveBeenCalledTimes(1);
  expect(fetchUserSpy).toHaveBeenCalledWith("42");

  expect(sendUserSpy).toHaveBeenCalledTimes(1);
  expect(sendUserSpy).toHaveBeenCalledWith(resDbUser);
});

もし、spyOnした対象にmockReturnValueを指定しない場合、本物の関数がよばれますが、呼び出し記録はされているので、toHaveBeenCalledTimesでそれを検証することができます。

  const sendUserSpy = jest
    .spyOn(MessageClient.prototype, "sendUser");

クラス自体の置き換え例

jest.mock("../src/external", () => ({
  DatabaseClient: jest.fn(),
  MessageClient: jest.fn(),
}));

const service = require("../src/service");
const { DatabaseClient, MessageClient } = require("../src/external");

afterEach(() => {
  jest.restoreAllMocks();
});

test("sendUserInfo: Mock 的に回数と引数を厳密に検証", () => {
  const resDbUser = { id: "42", display_name: "テスト太郎" };

  DatabaseClient.mockImplementation(() => ({
    fetchUser: jest.fn().mockReturnValue(resDbUser),
  }));

  const sendUserMock = jest.fn().mockReturnValue(true);

  MessageClient.mockImplementation(() => ({
    sendUser: sendUserMock,
  }));

  const act = service.sendUserInfo("42");

  expect(act).toBe(true);

  // 「期待通りの回数・引数でしか呼ばれていないこと」をここで検証
  expect(sendUserMock).toHaveBeenCalledTimes(1);
  expect(sendUserMock).toHaveBeenCalledWith(resDbUser);
});

実世界のまとめ

実世界ではGerard Meszarosが示した古典的なテストダブルの定義になっていません。
テストダブル全体を指す用語としてモックが使われることがあります。
狭義のモックオブジェクトについては事前に期待値を登録するとは限らず、使用状況を記録しておき、後で検証するというGerard Meszarosの定義するテストスパイが該当するケースが多いです。
また、Meszarosの定義するスタブだけの機能はテストツールとして特別に提供されるものではなく、Meszarosの定義するテストスパイやモックオブジェクトが使用されています。
スパイといった場合、Gerard Meszarosの定義した使用状況を記録するスタブという使い方と実関数の使用状況を記録する使い方になっている場合があります。

今日では古典的なテストダブルの分類を使用して明確に分けるというのは不可能で、複数の性質が混ざり合わざるを得ない状況です。

その他のテストダブル

「コード置き換え」から一段引いて見たときに、サブシステム/インフラ丸ごとを差し替えるものも広義のテストダブルと言えると思います。
そういったものの例をいくつか紹介します。

  • インメモリDB
    • テスト中にデータベースをインメモリ実装に置き換える。
      • SQLite の :memory: を使う、MySQL/PostgreSQL を Docker 上でメモリストレージにする等。
    • SQLiteのmemoryに簡単に置き換えたり、DockerでMySQLなどをテスト用に立ててる場合は、そのストレージをmemoryにする。
    • Meszaros 的分類だと代表的なFake(本物に近い動作をする代替実装)とされる。
  • Mock Service Worker
    • ブラウザ/Node.js で HTTP/GraphQL のリクエストを ネットワーク層でインターセプト してモックオブジェクトとするライブラリ。
    • サブシステムとしての Web API を Stub/Fake として置き換える ことができる。
  • WireMock
    • JVM 向けの HTTP モックサーバ。Java ライブラリとしてもスタンドアロンプロセスとしても動作
    • 「外部 HTTP サービスのスタンドアロン Fake 兼 Mock」として使える。
    • プロキシとして動かして本物の通信を記録してスタブを作成することができる。
  • BigQuery Emulator
    • 動作するBigQueryのエミュレータ。Dockerコンテナとして動作する。
    • 本物との挙動差はあるとはいえ、ローカルでSQLの動作確認ができる。Fakeにあたる。
  • fake-gcs-server
    • Google Cloud Storage API をエミュレートする OSS。スタンドアロン or Docker
    • Fakeにあたる。
  • moto
    • AWS の各サービスをローカルでエミュレートする。Fakeにあたる
    • pythonのみ
  • LocalStack
    • AWSのSES,SQS,DynamoDBなどの動作をエミュレートするコンテナ。Fakeといえる
    • 言語依存はなく、ローカルで AWS 一部サービスの動作確認が行える
    • 課金をすることで使用できる機能が増える
  • MailHog
    • Fake SMTP サーバ。アプリの SMTP 送信先を MailHog に向けると、メールは実際の外部には送られず、Web UI や API 経由で確認できる。
    • 誤送信を防ぎつつ、メール本文やリンクを UI から確認できるので、メール配送サブシステムの Fakeにあたる

Summary

In this article, we have reviewed the classic test doubles organized by Gerard Meszaros.
In the real world, these definitions are not strictly followed, and "mock" tends to be used as an umbrella term for all test doubles.
Even the narrowly defined meanings of "mock" and "spy" vary slightly across different frameworks.
This means that when a developer accustomed to one framework starts using another, they may encounter unexpected behavior due to their assumptions.
When using any test double framework, it is advisable to first clarify what that tool means by "mock," "spy," and "stub" before using it.

Does that mean Meszaros's classification is meaningless today? Not at all.
Today, test double frameworks are a blend of multiple characteristics. There is still value in decomposing and understanding those different characteristics.

Discussion