
This walks you through the four main ways to test PydanticAI agents without burning API credits on every test run. TestModel gives you deterministic responses, FunctionModel lets you write custom logic that inspects messages and decides what to return, VCR cassettes record and replay real API calls, and inline snapshots auto-update your assertions. The gates section is worth reading if you use VCR or snapshots, it's a four-step checklist that keeps you from accidentally rewriting files you didn't mean to touch. Good coverage of tool testing and dependency mocking too. If you're writing agents in production, you'll use at least two of these patterns.
$ npx -y skills add existential-birds/beagle --skill pydantic-ai-testing --agent claude-codeInstalls into .claude/skills of the current project.
Use TestModel for tests without API calls:
import pytest
from pydantic_ai import Agent
from pydantic_ai.models.test import TestModel
def test_agent_basic():
agent = Agent('openai:gpt-4o')
# Override with TestModel for testing
result = agent.run_sync('Hello', model=TestModel())
# TestModel generates deterministic output based on output_type
assert isinstance(result.output, str)
from pydantic_ai.models.test import TestModel
# Custom text output
model = TestModel(custom_output_text='Custom response')
result = agent.run_sync('Hello', model=model)
assert result.output == 'Custom response'
# Custom structured output (for output_type agents)
from pydantic import BaseModel
class Response(BaseModel):
message: str
score: int
agent = Agent('openai:gpt-4o', output_type=Response)
model = TestModel(custom_output_args={'message': 'Test', 'score': 42})
result = agent.run_sync('Hello', model=model)
assert result.output.message == 'Test'
# Seed for reproducible random output
model = TestModel(seed=42)
Sponsors