Testing LLM-powered agents is one of the most underrated problems in AI engineering. The difficulty is not just philosophical (“how do you assert on probabilistic output?”) — it is deeply practical. Test suites that worked fine for deterministic microservices break down hard when the system under test can reason, hallucinate, or change behavior based on prompt phrasing.
I have spent the last several weeks stress-testing the testing ecosystems of three major frameworks — LangGraph, CrewAI, and the Anthropic Agent SDK — across unit testing, integration testing, and mocking strategies. The results are uneven in ways that will directly affect your CI/CD pipeline decisions.
Why Agent Testing Is Different (And Harder)
Before getting into framework specifics, it is worth being precise about what makes agent testing structurally different from testing conventional software.
Nondeterminism: Even at temperature=0, LLMs are not fully deterministic across model versions, context windows, or provider infrastructure changes. A test that passed Tuesday may fail Thursday — same code, same inputs.
Tool invocation variance: Agents may choose to call tools in different sequences to reach the same correct end state. A naive assertion on “did the agent call tool X first?” will produce false failures.
Cascading context: In multi-agent systems, one agent’s output is another’s input. Errors amplify. A mocking strategy that isolates one agent but not another creates a test that is simultaneously too narrow and too fragile.
Latency and cost at test time: Running a full integration test suite against a live LLM API costs real money and takes real time. A 50-test suite hitting Claude Opus 4.6 can cost $20–$40 per run and take 15+ minutes. This matters for PR gates.
Good framework testing support addresses all of these. Let us see how each one stacks up.
LangGraph: Graph-Native Testing With Structural Hooks
LangGraph’s graph-based execution model is simultaneously its biggest strength and its most underappreciated asset for testing. Because every agent workflow is a typed state graph, you can intercept and validate at the node level.
Unit Testing LangGraph Nodes
Each node in a LangGraph graph is just a Python function that accepts and returns a typed state dict. This makes unit testing at the node level straightforward:
from myagent.nodes import research_node
from myagent.state import AgentState
def test_research_node_populates_sources():
initial_state = AgentState(
messages=[{"role": "user", "content": "What is RAG?"}],
sources=[],
final_answer=None
)
result = research_node(initial_state)
assert len(result["sources"]) > 0
assert all("url" in s for s in result["sources"])
The key advantage here: research_node is a pure function with typed I/O. You can test it without spinning up the graph or hitting an LLM. This is genuine unit testing — fast, cheap, deterministic — and LangGraph’s architecture makes it natural.
Mocking LLM Calls in LangGraph
LangGraph integrates tightly with LangChain’s runnable interface, which means you can swap in a FakeListChatModel or a ChatOpenAI mock with minimal ceremony:
from langchain_core.language_models.fake import FakeListChatModel
from myagent.graph import build_graph
def test_graph_with_mock_llm():
mock_llm = FakeListChatModel(responses=[
'{"action": "search", "query": "LangGraph docs"}',
'{"action": "finish", "answer": "LangGraph is a graph-based agent framework."}',
])
graph = build_graph(llm=mock_llm)
result = graph.invoke({"messages": [{"role": "user", "content": "Explain LangGraph"}]})
assert result["final_answer"] is not None
The FakeListChatModel returns scripted responses in sequence, which lets you drive specific execution paths deterministically. This is good — but it requires that your graph be built with LLM injection in mind from the start. Graphs that hardcode the LLM inside node closures are much harder to test this way.
Integration Testing with LangGraph Studio Traces
LangGraph Cloud (and local langgraph dev) exposes thread-level traces that you can assert on programmatically. For integration tests, this is powerful:
from langgraph_sdk import get_client
async def test_full_pipeline_integration():
client = get_client()
thread = await client.threads.create()
run = await client.runs.create(
thread_id=thread["thread_id"],
assistant_id="my-agent",
input={"messages": [{"role": "user", "content": "Summarize Q3 earnings"}]},
)
result = await client.runs.join(thread["thread_id"], run["run_id"])
assert result["status"] == "success"
assert "earnings" in result["values"]["final_answer"].lower()
Verdict on LangGraph testing: The node-as-function model is genuinely excellent for unit testing. Mocking is clean if you dependency-inject the LLM. Integration testing via SDK is functional but requires LangGraph Cloud or a local server, adding infrastructure overhead. Score: 8/10 for testability.
CrewAI: Role-Based Agents With Blunt Testing Surfaces
CrewAI’s design philosophy centers on role-playing agents organized into crews. It is remarkably fast to get running — but that same opinionated abstraction makes testing significantly harder.
The Unit Testing Problem in CrewAI
CrewAI agents are configured via high-level YAML or Python class definitions. The Agent, Task, and Crew abstractions encapsulate a lot of behavior — including LLM calls, tool invocations, and inter-agent delegation — in ways that resist decomposition:
from crewai import Agent, Task, Crew
researcher = Agent(
role="Research Analyst",
goal="Find and summarize recent AI papers",
backstory="Expert in machine learning literature",
tools=[SerperDevTool()],
llm="claude-opus-4-6"
)
task = Task(
description="Research the latest breakthroughs in agent memory systems",
agent=researcher,
expected_output="A 500-word summary with citations"
)
There is no clean seam to insert a mock LLM here without patching at the class level. The standard approach is unittest.mock.patch:
from unittest.mock import patch, MagicMock
import pytest
@patch("crewai.agent.Agent._execute_core_task")
def test_researcher_produces_output(mock_execute):
mock_execute.return_value = "Mocked research summary with citations."
crew = Crew(agents=[researcher], tasks=[task])
result = crew.kickoff()
assert "summary" in result.raw.lower()
This works, but it is fragile. You are patching internal implementation details of CrewAI, which means your tests will break with framework version upgrades — a maintenance burden that compounds over time.
CrewAI’s Built-in Testing Tools
CrewAI 0.80+ introduced crew.test() and crew.train() methods, which represent the framework’s first-class answer to validation:
# Run n iterations and collect quality metrics
crew.test(n_iterations=5, openai_model_name="gpt-4o")
This is an interesting approach — it treats testing as a statistical exercise over multiple runs, which is philosophically sound for nondeterministic systems. However, it is expensive (5 live LLM calls per test) and returns qualitative scores rather than pass/fail assertions, making it difficult to integrate into standard CI pipelines.
Integration Testing CrewAI Flows
CrewAI’s Flow abstraction (introduced for structured state management) is easier to integration test than raw Crews because flows expose explicit state transitions:
from crewai.flow.flow import Flow, start, listen
from pydantic import BaseModel
class ResearchState(BaseModel):
topic: str = ""
summary: str = ""
approved: bool = False
class ResearchFlow(Flow[ResearchState]):
@start()
def initiate_research(self):
self.state.topic = "Agent memory systems"
@listen(initiate_research)
def run_research_crew(self):
result = research_crew.kickoff(inputs={"topic": self.state.topic})
self.state.summary = result.raw
def test_flow_state_transitions():
flow = ResearchFlow()
# Mock the crew kickoff
with patch.object(research_crew, "kickoff") as mock_kickoff:
mock_kickoff.return_value = MagicMock(raw="Mocked summary content")
flow.kickoff()
assert flow.state.summary == "Mocked summary content"
assert flow.state.topic == "Agent memory systems"
Verdict on CrewAI testing: The high-level abstractions that make CrewAI fast to prototype make it slow to test rigorously. crew.test() is a smart idea that does not map to conventional CI workflows. Mocking requires patching internals. The Flow abstraction is a step in the right direction. Score: 5/10 for testability.
Anthropic Agent SDK: Minimal Surface, Maximum Control
The Anthropic Agent SDK (Python) takes a deliberately minimal approach. Rather than providing opinionated orchestration, it gives you primitives — client.messages.create() with tools — and lets you compose from there. This simplicity is a double-edged sword for testing.
Unit Testing With the SDK
Because SDK-based agents are typically structured as Python classes or functions that call client.messages.create(), the testing surface maps cleanly to standard Python testing patterns:
from anthropic import Anthropic
from myagent import ResearchAgent
def test_agent_formats_tool_call_correctly():
agent = ResearchAgent(client=mock_client)
response = agent.build_tool_call_message("Search for LangGraph docs")
assert response["role"] == "user"
assert any(block["type"] == "tool_use" for block in response.get("content", []))
The SDK’s client can be replaced with a mock at construction time, which is exactly what you want for unit testing. No internal patching required.
Mocking the Anthropic API
Anthropic provides official test tooling via anthropic.lib.streaming test helpers, and the SDK’s architecture makes mock injection clean:
import pytest
from unittest.mock import MagicMock, AsyncMock
from anthropic.types import Message, ContentBlock, TextBlock
@pytest.fixture
def mock_anthropic_client():
client = MagicMock()
client.messages.create.return_value = Message(
id="msg_test_001",
type="message",
role="assistant",
content=[TextBlock(type="text", text="The answer is 42.")],
model="claude-sonnet-4-6",
stop_reason="end_turn",
usage={"input_tokens": 100, "output_tokens": 20}
)
return client
def test_agent_handles_simple_response(mock_anthropic_client):
from myagent import SimpleAgent
agent = SimpleAgent(client=mock_anthropic_client)
result = agent.run("What is the answer?")
assert result == "The answer is 42."
mock_anthropic_client.messages.create.assert_called_once()
This pattern is clean, explicit, and stable across SDK versions because you are mocking the public API surface (client.messages.create), not framework internals.
Integration Testing Multi-Turn Conversations
For integration tests that need to exercise real multi-turn tool use loops, the SDK’s explicit message structure makes assertions straightforward:
import pytest
from myagent import ToolUseAgent
@pytest.mark.integration
def test_tool_use_loop_terminates():
"""Agent should use search tool, get results, then produce final answer."""
agent = ToolUseAgent(client=real_anthropic_client)
result = agent.run("What is the capital of France?")
# Assert tool was invoked
assert any(
msg["role"] == "tool"
for msg in agent.message_history
)
# Assert conversation terminated
assert result.stop_reason == "end_turn"
assert "Paris" in result.content[0].text
The explicit message history that SDK-based agents maintain is a testing asset — you can walk the entire conversation trace in assertions, something that CrewAI makes opaque by default.
Verdict on SDK testing: The minimalism pays dividends in testability. No opaque internals to patch, clean mock injection, explicit message traces. The tradeoff is that you build more scaffolding yourself. Score: 9/10 for testability.
Benchmarking Summary: Testing Overhead Across Frameworks
Based on hands-on evaluation across a 50-test suite (20 unit, 20 integration, 10 mock-based):
| Metric | LangGraph | CrewAI | Anthropic Agent SDK |
|---|---|---|---|
| Unit test setup time | Low | Medium-High | Low |
| Mock injection approach | Constructor/runnable swap | Internal patch | Constructor injection |
| Mock fragility (version upgrade risk) | Low | High | Low |
| Integration test infrastructure needed | LangGraph server | None | None |
| Full suite execution time (mocked) | ~45s | ~90s | ~30s |
| Full suite execution time (live LLM) | ~12min | ~18min | ~10min |
| Nondeterminism handling | Good (FakeListChatModel) | Poor | Good (explicit mock) |
| CI/CD integration difficulty | Medium | High | Low |
The Anthropic Agent SDK wins on testability largely because it does not abstract away the LLM boundary. LangGraph is close behind, with the caveat of integration test infrastructure requirements. CrewAI’s opinionated abstractions impose real testing debt.
Cross-Framework Mocking Strategies That Actually Work
Regardless of framework, a few mocking strategies consistently outperform others in production test suites:
1. Record-and-Replay With VCR.py
The vcrpy library records real API interactions to cassette files and replays them in tests. This is the most accurate mock strategy because the responses are real:
import vcr
@vcr.use_cassette("fixtures/research_agent_cassette.yaml")
def test_research_agent_with_cassette():
agent = ResearchAgent(client=Anthropic())
result = agent.run("Summarize the state of agent testing")
assert len(result) > 100
Tradeoff: Cassettes go stale when behavior changes intentionally. Treat them as fixtures that need periodic refresh.
2. Semantic Assertion Libraries
For assertions on LLM output quality, tools like deepeval and promptfoo provide semantic matchers:
from deepeval import assert_test
from deepeval.test_case import LLMTestCase
from deepeval.metrics import AnswerRelevancyMetric
def test_answer_relevancy():
test_case = LLMTestCase(
input="What is LangGraph?",
actual_output=agent.run("What is LangGraph?"),
expected_output="LangGraph is a framework for building stateful agent workflows as graphs."
)
assert_test(test_case, [AnswerRelevancyMetric(threshold=0.7)])
This bridges the gap between conventional boolean assertions and the probabilistic reality of LLM output.
3. Deterministic Fallback Patterns
For workflows where you want to assert on tool call sequences rather than output content, structuring your agent to log invocations to a trace store enables behavioral assertions without content assertions:
def test_agent_calls_search_before_summarize():
tracer = InvocationTracer()
agent = ResearchAgent(client=mock_client, tracer=tracer)
agent.run("Research AI testing frameworks")
tool_sequence = [inv.tool_name for inv in tracer.invocations]
assert tool_sequence.index("search") < tool_sequence.index("summarize")
Recommendations: Choosing Your Testing Strategy
If you are on LangGraph: Invest in node-level unit tests first. The graph architecture rewards this. Use FakeListChatModel for fast mock suites and reserve LangGraph Cloud traces for pre-deploy integration tests.
If you are on CrewAI: Prioritize Flow-based architectures over raw Crew for anything you need to test seriously. Use VCR cassettes rather than internal patching to reduce maintenance burden. Accept that crew.test() is for quality evaluation, not CI gating.
If you are on Anthropic Agent SDK: Lean into the clean mock injection model. Build a shared mock_client fixture library early in the project. The SDK’s explicit message history is a testing superpower — use it.
For all frameworks: Separate your test suite into three tiers — fast mocked unit tests (run on every commit), integration tests with live LLM (run on PR merge), and quality/semantic tests (run on release candidates). The cost and time profiles are too different to run them in the same CI stage.
Final Take
Agent testing is not a solved problem in any of these frameworks — but the gap between best and worst is substantial. The Anthropic Agent SDK’s minimalism makes it the most testable by default. LangGraph’s explicit graph structure earns it a close second. CrewAI’s high-level abstractions trade testability for rapid prototyping speed, a tradeoff that becomes increasingly expensive as systems move toward production.
The frameworks that will win in production AI engineering are the ones that treat testing as a first-class concern. Right now, that race is still being run.
Want to compare how these frameworks handle observability and tracing alongside testing? Check out our agent observability stack comparison for the full picture on what happens after your tests pass.
Running benchmarks of your own? Our framework cost efficiency analysis covers token usage patterns that directly affect your integration test economics.