> ## Documentation Index
> Fetch the complete documentation index at: https://cndoc-langchain.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 单元测试

> 使用模拟聊天模型和内存持久化，在不调用 API 的情况下测试智能体逻辑。

单元测试在隔离环境中运行智能体中细小、确定性的部分。通过将真实大语言模型替换为内存模拟对象（也称为测试夹具），您可以编写精确的响应（文本、工具调用和错误），从而使测试快速、免费且可重复，无需 API 密钥。

## 模拟聊天模型

LangChain 提供了 [`GenericFakeChatModel`](https://reference.langchain.com/python/langchain-core/language_models/fake_chat_models/GenericFakeChatModel) 用于模拟文本响应。它接受一个响应迭代器（[`AIMessage`](https://reference.langchain.com/python/langchain-core/messages/ai/AIMessage) 对象或字符串），并在每次调用时返回一个响应。它支持常规和流式使用。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel

model = GenericFakeChatModel(messages=iter([
    AIMessage(content="", tool_calls=[ToolCall(name="foo", args={"bar": "baz"}, id="call_1")]),
    "bar"
]))

model.invoke("hello")
# AIMessage(content='', ..., tool_calls=[{'name': 'foo', 'args': {'bar': 'baz'}, 'id': 'call_1', 'type': 'tool_call'}])
```

如果我们再次调用模型，它将返回迭代器中的下一个项目：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
model.invoke("hello, again!")
# AIMessage(content='bar', ...)
```

## InMemorySaver 检查点存储器

为了在测试期间启用持久化，您可以使用 [`InMemorySaver`](https://reference.langchain.com/python/langgraph/checkpoints/#langgraph.checkpoint.memory.InMemorySaver) 检查点存储器。这允许您模拟多轮对话以测试依赖状态的行为：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langgraph.checkpoint.memory import InMemorySaver

agent = create_agent(
    model,
    tools=[,
    checkpointer=InMemorySaver()
)

# 第一次调用
agent.invoke(
    {"messages": [HumanMessage(content="I live in Sydney, Australia")]},
    config={"configurable": {"thread_id": "session-1"}}
)

# 第二次调用：第一条消息已持久化（悉尼位置），因此模型返回 GMT+10 时间
agent.invoke(
    {"messages": [HumanMessage(content="What's my local time?")]},
    config={"configurable": {"thread_id": "session-1"}}
)
```

## 后续步骤

了解如何使用真实模型提供商 API 测试您的智能体，请参阅[集成测试](/oss/python/langchain/test/integration-testing)。

***

<div className="source-links">
  <Callout icon="terminal-2">
    [连接这些文档](/use-these-docs) 到 Claude、VSCode 等，通过 MCP 获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/langchain/test/unit-testing.mdx) 或 [提交问题](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
