Skip to content
Blog

Mocking Tools in Unit Tests: Building Predictable Agent Test Suites

How to isolate ADK agents from external side-effects using tool mocking, fake declarations, unittest.mock patches, and deterministic assertion harnesses in CI.

Published on • November 28, 2026

AI Assistant

Unit-testing an AI agent without mocking its tools turns deterministic test suites into flaky, expensive integration runs. If a test turn makes live Stripe payments, queries live production databases, or pings third-party REST endpoints, failures reflect network conditions rather than agent logic. Testing ADK agents requires isolating tool execution while preserving the exact schema contracts that the model inspects.

This tutorial covers the two primary strategies for tool isolation in ADK: swapping tools with deterministic fakes at instantiation, and intercepting calls via unittest.mock and before_tool_callback gates.

The testing spectrum: unit vs evaluation

Testing agentic workflows spans three distinct tiers:

Test tierTargetTool behaviorLLM involvementExecution speed
Schema unit testsTool signatures, types, docstringsNever executedNone (pure Python inspection)< 10ms
Tool unit testsFunction logic, error handlingExecuted with test fixturesNone< 50ms
Agent harness testsTool selection, orchestration, stateMocked responses / canned returnsMocked LLM or cheap model100ms – 1s
Integration evalsEnd-to-end task completionSandboxed live servicesProduction model tier5s – 30s

Keeping the first three tiers hermetic and fast guarantees that CI runs reliably on every commit without consuming external API quotas.

Asserting the generated tool schema

Before testing execution, assert that your tool generates the exact JSON schema the model expects. If a developer alters a type hint or drops a default value, the model’s tool-calling accuracy degrades silently:

import pytest
from google.adk.tools import FunctionTool

def fetch_customer_profile(customer_id: str, include_billing: bool = False) -> dict:
    """Fetch customer profile data.

    Args:
        customer_id (str): The unique customer UUID.
        include_billing (bool): Whether to include active billing methods.
    """
    ...

def test_tool_declaration_schema():
    tool = FunctionTool(func=fetch_customer_profile)
    declaration = tool.get_declaration()

    assert declaration.name == "fetch_customer_profile"
    assert "customer_id" in declaration.parameters["required"]
    assert "include_billing" not in declaration.parameters["required"]
    assert declaration.parameters["properties"]["customer_id"]["type"] == "STRING"

This test executes in microseconds without invoking any LLM or runner infrastructure.

Replacing tools with deterministic fakes

For agent-level tests where you want to test whether the agent selects the right tool and handles the return structure, pass substitute callables into the agent definition:

import pytest
from google.adk import Agent
from google.adk.runners import Runner
from google.adk.sessions import InMemorySessionService

def fake_get_stock(symbol: str) -> dict:
    """Mock stock lookup returning deterministic values."""
    mock_data = {
        "GOOG": {"symbol": "GOOG", "price": 185.50, "status": "active"},
        "AAPL": {"symbol": "AAPL", "price": 220.00, "status": "active"}
    }
    return mock_data.get(symbol.upper(), {"error": "Symbol not found"})

@pytest.mark.asyncio
async def test_agent_with_fake_tool():
    agent = Agent(
        name="finance_assistant",
        model="gemini-3.8-flash",
        tools=[fake_get_stock]
    )
    runner = Runner(agent=agent, session_service=InMemorySessionService())
    
    events = []
    async for event in runner.run_async(user_id="test_user", session_id="test_sess", prompt="What is Google stock price?"):
        events.append(event)
    
    # Assert tool was selected and parsed
    tool_calls = [e for e in events if getattr(e, "tool_calls", None)]
    assert len(tool_calls) > 0
    assert tool_calls[0].tool_calls[0].name == "fake_get_stock"

Mocking tools with unittest.mock

When using an existing codebase where you cannot easily re-instantiate the agent with different tool lists, patch the underlying function using Python’s standard unittest.mock.patch:

from unittest.mock import AsyncMock, patch
import pytest

@pytest.mark.asyncio
async def test_order_refund_tool_mocked(test_runner):
    with patch("services.billing.refund_payment", new_callable=AsyncMock) as mock_refund:
        mock_refund.return_value = {"status": "success", "refund_id": "ref_999"}
        
        events = [e async for e in test_runner.run_async(
            user_id="u1", session_id="s1", prompt="Refund order ord_123"
        )]
        
        # Verify the underlying service was called with exact args
        mock_refund.assert_awaited_once_with(order_id="ord_123")

Mocking via before_tool_callback

A third, highly flexible pattern is installing an interceptor callback on the runner. This leaves the tool declared naturally to the LLM, but intercepts invocation right before execution:

def mock_interceptor_callback(tool, args, tool_context) -> dict | None:
    """Intercept tool execution and return canned payloads during tests."""
    if tool.name == "send_email_notification":
        # Return dict immediately to bypass real network send
        return {"status": "sent", "recipient": args.get("to"), "mocked": True}
    return None  # Let non-mocked tools proceed

Returning a dictionary short-circuits tool execution and supplies that dictionary directly back to the LLM turn as if the real tool returned it.

Takeaways

  • Distinguish tool schema tests (microseconds) from mock execution tests (sub-second) and live evals.
  • Always unit-test generated tool declarations in CI to catch parameter naming or optionality regressions.
  • Use deterministic fakes for predictable data fixtures and clean multi-turn agent testing.
  • unittest.mock.patch isolates underlying SDKs while leaving the tool function signature intact.
  • before_tool_callback allows runner-level mock interception without touching agent definitions.

Further reading