How to Test Your AI Agent with Google ADK (So It Doesn’t Embarrass You in Production)
From the publisher’s feed, collected in the ZeroLabs newsroom.
Why “it works on my machine” isn’t good enough for AI agents , and what Google’s Agent Development Kit does about itYou’ve built an AI agent. It’s brilliant. You ask it a question, and it nails the answer. You show it to your team, and they’re impressed. You demo it for stakeholders, and they’re ready to deploy.Then you push it to production, and it:Returns the wrong customer’s order historyCalculates revenue using last year’s tax rateTries to delete a database instead of querying itConfidently tells a customer their package was delivered to MarsWelcome to the world of probabilistic software.Traditional unit tests don’t work here. Your agent doesn’t execute the same way twice. The LLM might choose different tools, phrase answers differently, or even hallucinate entirely new “facts” between runs.So how do you test something that’s inherently non-deterministic?Google’s Agent Development Kit (ADK) has an answer, and it’s surprisingly elegant. This article shows you exactly how to build confidence in your AI agents before they meet real users.The Problem: Why Traditional Testing BreaksLet’s say you’re testing a traditional Python function:def calculate_revenue(orders): return sum(order['amount'] for order in orders)# Unit testassert calculate_revenue([{'amount': 100}, {'amount': 200}]) == 300Deterministic. Same input → same output. Every time. Forever.Now let’s test an AI agent:# You ask the agent"What was revenue last quarter?"# Run 1: Agent's thought process"I'll query the orders table, filter by Q4 2024, sum the amounts"→ Returns: "$1,247,832"# Run 2: Same question, different day"I should check the revenue_summary table for faster results"→ Returns: "$1,247,832"# Run 3: After a model update"Let me aggregate by month first, then sum"→ Returns: "$1,247,832"Same answer, three completely different execution paths. How do you write a test for that?And here’s the kicker: sometimes the agent gets creative:# Run 4: The agent has a bad day"I'll use the customer_lifetime_value metric"→ Returns: "$4,892,441" ❌ WRONG METRICYou need to test both:Did the agent get the right answer? (Outcome evaluation)Did the agent take a reasonable path to get there? (Trajectory evaluation)Traditional assert result == expected only covers #1, and even that's tricky with natural language responses.ADK’s Solution: Evaluate Trajectories, Not Just OutputsADK introduces a concept called trajectory evaluation , testing the sequence of steps your agent took, not just where it ended up.Here’s the mental model:Traditional Test: Input → [BLACK BOX] → Output ✓ADK Evaluation: Input → [Step 1 ✓] → [Step 2 ✓] → [Step 3 ✓] → Output ✓You define what a “good path” looks like, and ADK checks whether your agent stayed on it.Real Example: Analytics AgentLet’s say you have an agent that answers revenue questions. Here’s what you want to test:User Question:“What was net revenue in France last month?”Expected Trajectory:Agent identifies metric: net_revenueAgent identifies filter: country = 'FR'Agent determines time window: last monthAgent calls query_metric tool with correct parametersAgent returns result with proper formattingNot Acceptable:Agent writes raw SQL (should use semantic layer)Agent queries wrong metric (like gross_revenue)Agent uses wrong country code (like France instead of FR)Agent omits the time filter (scans entire table = $$$)Let’s see how to codify thisThe Two Testing Approaches: Unit vs. IntegrationADK supports two evaluation patterns, and understanding when to use each is critical.Approach 1: Test Files (Unit Tests)Use for: Fast, focused tests during active developmentStructure: One file = One session (potentially multiple turns)When to use:✅ You’re actively developing features✅ You want fast feedback in CI/CD✅ You’re testing specific behaviors✅ Sessions are simple (1–3 turns)File naming: anything_you_want.test.jsonExample: Testing that your agent correctly handles a simple revenue query{ "eval_set_id": "revenue_agent_basic_queries", "name": "Basic Revenue Query Tests", "description": "Unit tests for single-turn revenue queries", "eval_cases": [ { "eval_id": "france_revenue_last_month", "conversation": [ { "invocation_id": "test-001", "user_content": { "parts": [{"text": "What was net revenue in France last month?"}], "role": "user" }, "final_response": { "parts": [{"text": "Net revenue in France last month was $1,247,832.45"}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "filters": {"country": "FR"}, "start_date": "2025-12-01", "end_date": "2025-12-31" } } ], "intermediate_responses": [] } } ], "session_input": { "app_name": "revenue_agent", "user_id": "test_user", "state": {} } } ]}What’s being tested here| Component | Expected | What ADK Checks ||-------------|---------------------------|-----------------------------------------|| Tool Name | `query_metric` | Did agent use the right tool? || Metric | `net_revenue` | Did agent select correct metric? || Filter | `country = 'FR'` | Did agent parse country correctly? || Date Range | Last month (Dec 2025) | Did agent calculate dates correctly? || Response | Mentions amount + context | Is response formatted properly? |Approach 2: EvalSet Files (Integration Tests)Use for: Complex, multi-turn conversationsStructure: One file = Multiple sessions with multiple turns eachWhen to use:✅ You’re testing conversation flows✅ You need context from previous turns✅ You’re doing regression testing✅ Sessions are complex (4+ turns)File naming: anything_you_want.evalset.jsonExample: Testing a multi-turn conversation where context matters{ "eval_set_id": "revenue_agent_conversation_flow", "name": "Multi-Turn Revenue Analysis", "description": "Integration tests for conversational revenue queries", "eval_cases": [ { "eval_id": "revenue_comparison_conversation", "conversation": [ { "invocation_id": "turn-001", "user_content": { "parts": [{"text": "What was our revenue last month?"}], "role": "user" }, "final_response": { "parts": [{"text": "Total revenue last month was $4.2M across all countries."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "start_date": "2025-12-01", "end_date": "2025-12-31" } } ] } }, { "invocation_id": "turn-002", "user_content": { "parts": [{"text": "How does that compare to the previous month?"}], "role": "user" }, "final_response": { "parts": [{"text": "Revenue decreased 8.3% from November's $4.6M."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "start_date": "2025-11-01", "end_date": "2025-11-30" } } ] } }, { "invocation_id": "turn-003", "user_content": { "parts": [{"text": "Which country drove the decline?"}], "role": "user" }, "final_response": { "parts": [{"text": "Germany declined 23% ($380K drop), partially offset by France growing 8% ($120K gain)."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "group_by": ["country"], "start_date": "2025-11-01", "end_date": "2025-12-31" } } ] } } ], "session_input": { "app_name": "revenue_agent", "user_id": "test_user", "state": {} } } ]}Why this matters:Turn 2 references “previous month” (contextual) Turn 3 references “the decline” (requires memory from Turn 2) → Your agent must maintain conversation context correctlyThe Schema: Understanding What Goes WhereLet’s break down the test file structure piece by piece:Top-Level Structure{ "eval_set_id": "unique_identifier_for_this_test_suite", "name": "Human-Readable Name", "description": "What this test suite covers", "eval_cases": [ // Array of individual test cases ]}Each Test Case (Eval Case){ "eval_id": "unique_test_case_id", "conversation": [ // Array of turns (user messages + agent responses) ], "session_input": { "app_name": "your_agent_name", "user_id": "test_user_id", "state": {} // Initial session state (if any) }}Each Turn in the Conversation{ "invocation_id": "unique_id_for_this_turn", // What the user said "user_content": { "parts": [{"text": "User's question here"}], "role": "user" }, // What you expect the agent to say back "final_response": { "parts": [{"text": "Expected agent response"}], "role": "model" }, // What you expect to happen behind the scenes "intermediate_data": { "tool_uses": [ // Expected tool calls in order { "name": "tool_name", "args": { "param1": "value1", "param2": "value2" } } ], "intermediate_responses": [ // For multi-agent systems: expected sub-agent responses [ "sub_agent_name", [{"text": "Sub-agent's intermediate response"}] ] ] }}EvalSet├── eval_set_id (string)├── name (string)├── description (string)└── eval_cases (array) └── EvalCase ├── eval_id (string) ├── session_input │ ├── app_name (string) │ ├── user_id (string) │ └── state (object) └── conversation (array) └── Turn ├── invocation_id (string) ├── user_content │ ├── parts (array of text) │ └── role ("user") ├── final_response │ ├── parts (array of text) │ └── role ("model") └── intermediate_data ├── tool_uses (array) │ ├── name (string) │ └── args (object) └── intermediate_responses (array)Evaluation Criteria: How Strict Should You Be?ADK provides multiple ways to evaluate your agent. Think of these as different “lenses” for examining behavior.The Built-In CriteriaDefault ConfigurationIf you don’t specify criteria, ADK uses:{ "criteria": { "tool_trajectory_avg_score": 1.0, // 100% exact match required "response_match_score": 0.8 // 80% similarity required }}This is strict great for catching regressions, but might be too rigid during development.Custom ConfigurationCreate a test_config.json next to your test files:{ "criteria": { "tool_trajectory_avg_score": 0.9, // Allow 90% match (some flexibility) "response_match_score": 0.7, // More lenient on wording "hallucinations_v1": 0.95 // Very strict on factual accuracy }}Real-World RecommendationsFor CI/CD pipelines:{ "criteria": { "tool_trajectory_avg_score": 1.0, // Exact tool calls "response_match_score": 0.75 // Some wording flexibility }}Why: Fast, predictable, catches breaking changesFor production validation:{ "criteria": { "final_response_match_v2": 0.9, // Semantic equivalence "hallucinations_v1": 0.95, // No made-up facts "safety_v1": 0.99 // No harmful content }}Why: Slower but higher confidence, appropriate for pre-deploymentFor development iteration:{ "criteria": { "rubric_based_final_response_quality_v1": { "rubric": "Response is helpful and uses the correct metric" }, "rubric_based_tool_use_quality_v1": { "rubric": "Agent uses semantic layer instead of raw SQL" } }}Why: Flexible, focuses on intent rather than exact matchesFor development iteration:{ "criteria": { "rubric_based_final_response_quality_v1": { "rubric": "Response is helpful and uses the correct metric" }, "rubric_based_tool_use_quality_v1": { "rubric": "Agent uses semantic layer instead of raw SQL" } }}Why: Flexible, focuses on intent rather than exact matchesThree Ways to Run EvaluationsADK gives you three different interfaces for the same evaluation engine. Use the one that fits your workflow.Method 1: Web UI (adk web) - Interactive DevelopmentBest for: Building and refining test cases interactivelyWorkflow:adk web path/to/your/agentStep-by-step:Chat with your agent , Have normal conversationsNavigate to Eval tab , Right side of the interfaceCreate or select eval set , Organize tests logicallyClick “Add current session” , Saves conversation as test caseEdit the test case , Refine expected responses and tool callsRun evaluation , Configure thresholds and executeAnalyze results , Side-by-side comparison of expected vs. actualVisual Workflow:[Chat Interface] ↓ (have conversation)[Save to Eval Set] ↓ (click "Add current session")[Edit Test Case] ↓ (refine expectations)[Configure Metrics] ↓ (set thresholds)[Run Evaluation] ↓ (execute tests)[View Results] ↓ (pass/fail breakdown)[Debug with Trace View]Pro tip: Use the Trace tab to debug failures. It shows you:Every event in the agent’s executionRequest/response for each model callTool invocations with parametersVisual graph of the execution flowHover over trace rows to highlight corresponding messages. Click to drill into details.Method 2: pytest (pytest) - CI/CD IntegrationBest for: Automated testing in your build pipelineSetup:# tests/integration/test_revenue_agent.pyfrom google.adk.evaluation.agent_evaluator import AgentEvaluatorimport pytest@pytest.mark.asyncioasync def test_basic_revenue_queries(): """Test agent handles simple revenue queries correctly.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/fixtures/basic_queries.test.json" )@pytest.mark.asyncioasync def test_multi_turn_conversations(): """Test agent maintains context across turns.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/fixtures/conversations.evalset.json" )@pytest.mark.asyncio async def test_all_revenue_scenarios(): """Run entire test suite.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/integration/fixtures/" )Run in CI/CD:# In your CI pipeline (GitHub Actions, GitLab CI, etc.)pytest tests/integration/ -v --tb=shortBenefits:✅ Automatic regression detection✅ Blocks broken changes from merging✅ Runs on every commit✅ Integrates with existing test infrastructureMethod 3: CLI (adk eval) - One-Off ValidationBest for: Manual testing, pre-deployment validation, debugging specific issuesBasic usage:adk eval \ path/to/agent \ path/to/evalset.jsonWith custom config:adk eval \ path/to/agent \ path/to/evalset.json:test_001,test_005,test_012Run specific tests only:adk eval \ path/to/agent \ path/to/evalset.json:test_001,test_005,test_012This syntax means: “Run only test_001, test_005, and test_012 from the evalset”Multiple eval sets:adk eval \ path/to/agent \ tests/basic.evalset.json \ tests/advanced.evalset.json \ tests/edge_cases.evalset.jsonReal-World Example: Building a Test SuiteLet’s walk through creating a comprehensive test suite for our revenue analytics agent.Directory Structurerevenue_agent/├── __init__.py├── agent.py├── tools.py└── tests/ ├── unit/ │ ├── simple_queries.test.json │ ├── metric_validation.test.json │ └── error_handling.test.json ├── integration/ │ ├── conversations.evalset.json │ ├── complex_analysis.evalset.json │ └── test_config.json └── test_runner.pyUnit Tests: Simple QueriesFile: tests/unit/simple_queries.test.json{ "eval_set_id": "simple_revenue_queries", "name": "Simple Revenue Queries", "description": "Single-turn queries for basic metrics", "eval_cases": [ { "eval_id": "total_revenue_last_month", "conversation": [ { "invocation_id": "test-simple-001", "user_content": { "parts": [{"text": "What was total revenue last month?"}], "role": "user" }, "final_response": { "parts": [{"text": "Total revenue last month was $4.2M."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "start_date": "2025-12-01", "end_date": "2025-12-31" } } ] } } ], "session_input": { "app_name": "revenue_agent", "user_id": "test_user", "state": {} } }, { "eval_id": "revenue_by_country", "conversation": [ { "invocation_id": "test-simple-002", "user_content": { "parts": [{"text": "Show me revenue by country for Q4"}], "role": "user" }, "final_response": { "parts": [{"text": "Q4 revenue by country: US $1.8M, FR $1.2M, DE $0.9M, GB $0.3M"}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "group_by": ["country"], "start_date": "2025-10-01", "end_date": "2025-12-31" } } ] } } ], "session_input": { "app_name": "revenue_agent", "user_id": "test_user", "state": {} } } ]}Integration Tests: ConversationsFile: tests/integration/conversations.evalset.json{ "eval_set_id": "revenue_conversations", "name": "Multi-Turn Revenue Conversations", "description": "Test context retention and complex analysis", "eval_cases": [ { "eval_id": "comparative_analysis", "conversation": [ { "invocation_id": "conv-001-turn-1", "user_content": { "parts": [{"text": "What was revenue in France last quarter?"}], "role": "user" }, "final_response": { "parts": [{"text": "France revenue in Q4 was $1.2M."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "filters": {"country": "FR"}, "start_date": "2025-10-01", "end_date": "2025-12-31" } } ] } }, { "invocation_id": "conv-001-turn-2", "user_content": { "parts": [{"text": "How does that compare to Q3?"}], "role": "user" }, "final_response": { "parts": [{"text": "France Q4 revenue of $1.2M was up 15% from Q3's $1.04M."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "filters": {"country": "FR"}, "start_date": "2025-07-01", "end_date": "2025-09-30" } } ] } }, { "invocation_id": "conv-001-turn-3", "user_content": { "parts": [{"text": "What drove the growth?"}], "role": "user" }, "final_response": { "parts": [{"text": "The growth was driven by a 28% increase in order count (from 812 to 1,039 orders)."}], "role": "model" }, "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": { "metric_name": "order_count", "filters": {"country": "FR"}, "start_date": "2025-07-01", "end_date": "2025-12-31", "group_by": ["quarter"] } } ] } } ], "session_input": { "app_name": "revenue_agent", "user_id": "test_user", "state": {} } } ]}Test ConfigurationFile: tests/integration/test_config.json{ "criteria": { "tool_trajectory_avg_score": 0.9, "final_response_match_v2": 0.85, "hallucinations_v1": 0.95 }}Test RunnerFile: tests/test_runner.pyfrom google.adk.evaluation.agent_evaluator import AgentEvaluatorimport pytestclass TestRevenueAgent: @pytest.mark.asyncio async def test_simple_queries(self): """Fast unit tests for basic queries.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/unit/" ) @pytest.mark.asyncio @pytest.mark.slow async def test_conversations(self): """Integration tests for multi-turn conversations.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/integration/conversations.evalset.json" ) @pytest.mark.asyncio @pytest.mark.slow async def test_complex_analysis(self): """Integration tests for complex analytical workflows.""" await AgentEvaluator.evaluate( agent_module="revenue_agent", eval_dataset_file_path_or_dir="tests/integration/complex_analysis.evalset.json" )Run tests:# Fast tests only (CI on every commit)pytest tests/ -m "not slow"# All tests (nightly builds)pytest tests/ -v# Specific test suitepytest tests/test_runner.py::TestRevenueAgent::test_simple_queriesCommon Pitfalls (And How to Avoid Them)Pitfall 1: Tests Too RigidProblem: You require exact string matches for natural language responses"final_response": { "parts": [{"text": "Total revenue last month was $4.2M."}]}Agent says: “Last month’s total revenue was $4.2M.” → FAILS (different wording, same meaning)Solution: Use semantic matching instead{ "criteria": { "final_response_match_v2": 0.85 // LLM judges equivalence }}Pitfall 2: Testing Too Much in One CaseProblem: One eval case tests multiple unrelated behaviors{ "eval_id": "kitchen_sink_test", "conversation": [ {"text": "What's revenue?"}, {"text": "How many orders?"}, {"text": "List all customers"}, {"text": "Delete old data"} ]}When this fails, you don’t know which behavior broke.Solution: One eval case = One behavior{ "eval_id": "revenue_query", "conversation": [{"text": "What's revenue?"}]},{ "eval_id": "order_count_query", "conversation": [{"text": "How many orders?"}]}Pitfall 3: Ignoring Tool ArgumentsProblem: You only check that the right tool was called"tool_uses": [ { "name": "query_metric" // Missing: args validation! }]Agent calls query_metric with wrong parameters → PASSES (but shouldn't)Solution: Always validate arguments"tool_uses": [ { "name": "query_metric", "args": { "metric_name": "net_revenue", "filters": {"country": "FR"}, "start_date": "2025-12-01", "end_date": "2025-12-31" } }]Pitfall 4: Not Testing Edge CasesProblem: Only testing happy pathsSolution: Build a comprehensive test matrix✅ Test happy paths✅ Test invalid inputs ("Show me revenue for Atlantis")✅ Test missing data ("What's revenue for next year?")✅ Test ambiguous queries ("What's revenue?" - which metric? which time period?)✅ Test permission boundaries (user requests data they can't access)✅ Test rate limits (too many queries in short time)Pitfall 5: Forgetting to Version Your TestsProblem: Tests change without historySolution: Treat tests like codegit add tests/git commit -m "Add edge case tests for date parsing"git tag -a v1.2.0-tests -m "Test suite version 1.2.0"Best Practices: The Testing PyramidApply the classic testing pyramid to AI agents: /\ / \ Integration Tests (10%) / \ Complex multi-turn conversations /------\ / \ Unit Tests (70%) / \ Simple single-turn queries /____________\ Manual Exploratory Testing (20%) Ad-hoc conversations in UIUnit Tests (70% of coverage):Single-turn queriesBasic tool invocationsInput validationError handlingRun on every commit (Integration Tests (10% of coverage):Multi-turn conversationsComplex tool orchestrationContext retentionRun on merge to main (Manual Testing (20% of time):New featuresEdge cases you haven’t codified yetUX explorationContinuous throughout developmentAdvanced: Testing Multi-Agent SystemsWhen your agent delegates to sub-agents, you need to test intermediate responses too.Example architecture:RootAgent├── DataRetrievalAgent (gets data from BigQuery)├── AnalysisAgent (performs calculations)└── ResponseGenerationAgent (formats answer)Test structure:{ "intermediate_data": { "tool_uses": [ { "name": "query_metric", "args": {"metric_name": "net_revenue"} } ], "intermediate_responses": [ [ "DataRetrievalAgent", [{"text": "I retrieved revenue data: $4.2M total"}] ], [ "AnalysisAgent", [{"text": "Compared to last month, this is down 8.3%"}] ] ] }, "final_response": { "parts": [{"text": "Revenue last month was $4.2M, down 8.3% from November."}] }}This tests:✅ Root agent delegates correctly✅ Each sub-agent produces expected output✅ Final response synthesizes everythingDebugging Failed Tests: The Trace ViewWhen a test fails, the Trace View in adk web is your best friend.What it shows:Timeline View:├─ User message received├─ Agent determines intent│ ├─ LLM Request: {...}│ └─ LLM Response: {intent: "query_revenue"}├─ Agent calls query_metric│ ├─ Tool args: {metric: "net_revenue", ...}│ └─ Tool response: {value: 4200000}├─ Agent formats response│ ├─ LLM Request: {...}│ └─ LLM Response: "Revenue was $4.2M"└─ Final response sentInteractive features:Hover over traces → Highlights corresponding message in chatClick trace → Opens detailed panel with:Event data (raw JSON)Request sent to modelResponse from modelGraph visualization of control flowDebugging workflow:Test fails in pytestOpen adk webReproduce the failing conversationOpen Trace tabFind where behavior diverged from expectedUpdate test or fix agent logicRe-run pytestResources & Next StepsOfficial Documentation:Google ADK Documentation , Complete framework guideADK Evaluation , Official evaluation documentationADK Python GitHub Repository , Source code and examplesHow to Test Your AI Agent with Google ADK (So It Doesn’t Embarrass You in Production) was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.