Skip to main content
Unit tests exercise small, deterministic pieces of your agent in isolation. By replacing the real LLM with an in-memory fake (AKA fixture), you can script exact responses (text, tool calls, and errors) so tests are fast, free, and repeatable without API keys.

Mock chat model

LangChain provides GenericFakeChatModel for mocking text responses. It accepts an iterator of responses (AIMessage objects or strings) and returns one per invocation. It supports both regular and streaming usage.
If we invoke the model again, it will return the next item in the iterator:

Return plain text with FakeListChatModel

For tests that only need text responses, use FakeListChatModel. It takes a list of strings, so you do not construct AIMessage objects:
FakeListChatModel cycles through its responses. When invoked more times than the list has entries, it starts again from the first response. Use GenericFakeChatModel when you need exact control of each turn, such as tool calls.

Test a tool-calling loop

An agent typically calls a tool, then uses the result to answer. To script this loop, give the fake model two responses: a tool call, then a final answer. GenericFakeChatModel does not implement bind_tools, which create_agent calls when you pass tools. Subclass it so that bind_tools returns the model unchanged:

Share fake models with pytest fixtures

To reuse a fake model across tests, return it from a pytest fixture. This example uses FakeToolCallingModel and get_weather from the previous section:
GenericFakeChatModel reads responses from an iterator, and an exhausted iterator cannot be reused. Keep the fixture at the default function scope, which builds a fresh model for each test. A module or session scope shares one iterator, so later tests fail once it runs out.

InMemorySaver checkpointer

To enable persistence during testing, you can use the InMemorySaver checkpointer. This allows you to simulate multiple turns to test state-dependent behavior:

Next steps

Learn how to test your agent with real model provider APIs in Integration testing.