Testing Voice Agent Tool Call Workflows: Mocking, Assertions and Sandbox Patterns

Sumanyu Sharma
Sumanyu Sharma
Founder & CEOAn industry expert reviewed this article for accuracy and quality., Voice AI Security and Testing Pioneer

Hamming protects 10K+ voice agents in production.

· Updated · 12 min read

Testing Voice Agent Tool Call Workflows: Mocking, Assertions and Sandbox Patterns

Testing voice agent tool call workflows means proving that a voice agent called the right tools, in the right order, with the right arguments, and left the backend in the right terminal state. The transcript is one witness. The tool trace is the one that decides.

This page is for engineers who own a voice agent that does things: looks up orders, updates addresses, books appointments, opens tickets, routes calls. If your agent answers questions and touches nothing, transcript-level evaluation is enough and this method is overkill.

The trap is that transcript scoring and tool-call testing feel like the same activity and are not. A team builds an LLM grader, scores a thousand calls as polite and accurate, and never notices that a slice of "your address is updated" calls, call it 4% as an illustrative rate, updated nothing, because no assertion ever read the tool log.

TL;DR: Test tool call workflows in four layers. Mock the external APIs with programmed responses and a captured call log. Assert a golden trajectory: expected tool sequence, arguments, and terminal state, with one trajectory per legitimate branch. Validate that spoken entities land in typed tool arguments through schema checks at the tool boundary. Assert that context collected early in the call reaches later tool calls intact. A call passes when all four layers agree, not when the transcript sounds right.

Methodology Note: This guide is based on Hamming's analysis of production voice agent calls where tool selection, argument quality, and workflow completion decided the caller outcome across 10K+ voice agents (2025-2026). We've tested agents built on Sierra, Decagon, ElevenLabs, LiveKit, and custom-built solutions.

Use these patterns to test agents you own or are authorized to assess, against mocks and fixtures rather than live customer systems.

Last Updated: November 2026

Related Guides:

How do I test voice agent tool call workflows?

Definition: Tool call workflow testing is the practice of asserting a voice agent's tool trace (which tools ran, in what order, with what arguments, returning what results) against an expected trajectory and terminal state, instead of grading only the conversation.

Each page in this cluster owns one piece, and the Related Guides list above maps them: this page owns the method itself, which is mocking, trajectory assertions, argument validation, and context passing. The sibling pages own isolation mechanics, the full workflow surface, per-tool contracts, authorization, and the worked calendar case.

Transcript Scoring Cannot See What the Tools Did

Scoring what the agent said misses what the tools did, in both directions. The agent can claim success after a failed write, and it can execute a write while verbally refusing. Neither failure appears in a transcript score.

What you gradeCatchesMisses
Transcript onlyTone, policy language, flow, spoken accuracySilent write failures, duplicate writes, wrong arguments, skipped lookups, tools fired during a spoken refusal
Tool trace onlyTool choice, order, arguments, resultsA correct backend action the caller never understood or confirmed
Both, asserted separatelyDisagreement between what was said and what was doneLittle; disagreement is the signal

The rule that follows: every workflow test asserts the transcript and the tool trace as separate witnesses, and fails when they disagree. "I've updated your address" with an empty call log is a failure. A refusal with a fired tool call is a worse one.

Mock the External APIs So Every Run Is Assertable

A mocked dependency gives you two things a live API cannot: programmed responses (including failures you can trigger on demand) and a complete, deterministic log of every call the agent's tools made. Python's standard library covers both without any vendor SDK. The unittest.mock documentation states that call_args_list is "a list of all the calls made to the mock object in sequence," that side_effect can be "a function to be called when the mock is called, an iterable or an exception," and that with create_autospec, mocked functions "will have their arguments checked and will raise a TypeError if they are called with the wrong signature."

import copyfrom unittest.mock import create_autospecclass OrderAPI:    """The real client your agent's tools wrap."""    def lookup_order(self, order_id: str) -> dict: ...    def update_shipping_address(self, order_id: str, address: dict) -> dict: ...# Mock with the real signatures enforcedmock_api = create_autospec(OrderAPI, instance=True)mock_api.lookup_order.return_value = {    "order_id": "ord_7714", "status": "processing", "editable": True,}mock_api.update_shipping_address.return_value = {"status": "updated"}# agent, run_voice_scenario, and build_tools are your own harness: the agent under test and the plumbing that exposes the mock as its toolsnew_address = {    "street": "2200 N Clark St", "city": "Chicago", "state": "IL", "postal_code": "60614",}run = run_voice_scenario(    agent, tools=build_tools(mock_api),    scenario="caller gives order ord_7714, has moved to 2200 N Clark St, Chicago, IL 60614, asks to change the shipping address",)# 1. Tool choice and arguments, from the captured call log.# Autospec binds positional and keyword calls to the real signature, so this# full-call assertion checks every address field, postal code included,# however the agent's tool passed the argument.mock_api.lookup_order.assert_called_once_with("ord_7714")mock_api.update_shipping_address.assert_called_once_with("ord_7714", address=new_address)# 2. Order: the lookup ran before the writenames = [name for name, _, _ in mock_api.method_calls]assert names.index("lookup_order") < names.index("update_shipping_address")# 3. Failure path: timeout on the first write, success on the retrymock_api.update_shipping_address.reset_mock()recorded = []def record_write(order_id, address):    recorded.append((order_id, copy.deepcopy(address)))  # autospec binds args to the real signature; deepcopy freezes the payload    if len(recorded) == 1:        raise TimeoutError("upstream 504")    return {"status": "updated"}mock_api.update_shipping_address.side_effect = record_writerun = run_voice_scenario(    agent, tools=build_tools(mock_api),    scenario="caller gives order ord_7714, has moved to 2200 N Clark St, Chicago, IL 60614, asks to change the shipping address",)assert len(recorded) == 2  # two transport attempts: one timeout, one retryassert recorded[0] == recorded[1]  # the retry re-sent the same payload, compared on frozen copies

Two details carry most of the value. create_autospec means a tool that drifts from the real client signature fails in CI instead of in production. And a side_effect function lets you script the dependency misbehaving while capturing signature-normalized, deep-copied payloads, so a payload mutated between attempts cannot make two different writes compare equal. That assertion is transport-level: it proves two identical requests, not one durable result, because a timeout can land after the backend commits. Proving exactly one durable write takes an idempotency key the backend enforces and the replay-and-count assertion shown in the calendar booking guide.

Mocks prove agent behavior, not integration behavior. The mock-or-sandbox decision comes down to what you need to see. When a write carries side effects you must watch land, such as a real row updated or a real event created and then cleaned up, a sandboxed real backend beats a mock, because the mock can only report that the call was made. The mock wins when you need programmed failures on demand and fast deterministic runs in CI; you cannot ask a real backend to time out on cue. Most workflows use both: mocks for every branch and failure path, one sandboxed pass to prove the integration itself. When the failure you are hunting lives in real auth, schemas, or provider quirks, move that dependency to a fixture-backed environment using the sandbox patterns; the full decision table and the isolation mechanics live there.

Golden Trajectory Assertions: Sequence, Arguments, Terminal State

A golden trajectory is the expected tool-call path for one workflow, written down before any call runs. It has three parts, asserted in this order:

  1. Sequence. The tools that must run, the order constraints between them, and the tools that must not appear. Reads before writes; verification before account-specific actions.
  2. Arguments. Each write carries values from verified context, matched field by field, not by "a booking tool was called."
  3. Terminal state. The workflow ends in exactly one of its defined end states: completed, declined with reason, or escalated. A call that ends mid-flow with a partial write is a failure even if every individual tool call looked fine.

Strictness is a per-workflow decision, and the open-source tooling makes the options concrete. The match modes documented for the open-source agentevals package are strict ("exact match of messages and tool calls in the same order"), unordered, subset ("agent calls only tools from reference"), and superset, and "by default, only tool calls with the same arguments to the same tool are considered equal."

Match modeUse forRisk
Strict order plus argumentsWrite paths: bookings, updates, refund requestsBrittle if harmless lookups vary between runs
UnorderedParallel reads where sequence is genuinely freeHides ordering bugs on paths where order is policy
Subset (no extra tools)Proving a refusal or lookup-only flow fired no writesSays nothing about missing required calls
Superset (extras allowed)Early development, exploratory promptsLets duplicate and stray writes pass

When flows legitimately branch, do not loosen the match. Write one golden trajectory per branch: the happy path, the slot-unavailable path, the verification-failed path. Each branch gets its own expected sequence and its own forbidden-tool list, and the test first classifies which branch the call took, then asserts that branch strictly. A single fuzzy trajectory that accepts all branches accepts most bugs too.

Agent runs are nondeterministic, so run each scripted case several times before trusting its trajectory. Absorb legitimate variation the same way you absorb branching: a per-branch trajectory or a branch classifier, never a looser match. A trajectory that flakes across identical runs is a finding about the agent, not a test to quarantine silently; write-path rows stay merge-blocking on the stable form.

Structured Output Validation: Spoken Entities Must Land as Typed Arguments

A voice workflow has a conversion problem text agents do not: "march third at three thirty" must become 2027-03-03T15:30 in a typed argument, through ASR, the model, and the tool schema. Each hop can corrupt it while the transcript still reads fine.

Start at the ASR layer. Deepgram's Smart Format feature, as one documented example, formats dates, times, currency amounts, phone numbers, emails, and URLs for English models, and in streaming mode an incomplete entity waits for more audio or up to 3 seconds of silence before formatting. Whatever ASR you use, test it with real spoken numbers: digit strings read in pairs, dates said as weekdays, amounts with "hundred" dropped.

Then enforce the schema at the tool boundary. For model-side arguments, OpenAI's function calling guide states that "setting strict to true will ensure function calls reliably adhere to the function schema," and requires additionalProperties: false with all fields listed as required. Schema conformance is the floor, not the test: a schema-valid wrong date passes every type check.

Spoken entityTypical corruptionAssertion at the tool boundary
Date and time"Friday at 3" resolved in the wrong timezone or weekArgument equals the fixture's expected ISO value, including offset
Phone numberDigits merged, dropped, or formatted inconsistently mid-streamNormalized E.164 string matches the number the fixture caller spoke
Amount"fifteen hundred" becoming 15.00 or 150000Integer minor units match the scripted amount exactly
Account or order IDLetter-digit confusion (A/8, B/D) in alphanumericsArgument matches a looked-up record, never raw transcription

Run these as scripted cases where the test knows what the fixture caller said, so the assertion is an equality check. The field-level evidence rules (what counts as caller support for an extracted value) are owned by the structured output validation checklist; the ASR accuracy guide covers measuring the transcription layer itself.

Dynamic Context Passing: What Was Verified Early Must Arrive Late

Long calls fail in a way single-turn tests never catch: the agent verifies the caller and looks up the account in the first minute, then six minutes later writes using a value it re-extracted from conversation instead of the verified context. The write is schema-valid, confident, and wrong.

Test context passing as its own case type:

  1. Script a scenario where the decisive value appears early: the caller gives their order number in turn 2, then the conversation detours through two unrelated questions.
  2. Plant a decoy late in the call: the caller mentions a different number ("my old order was 8812") without asking to act on it.
  3. Run the call and capture the full tool log from the mock.
  4. Assert the final write used the early, verified value: the order ID argument equals "ord_7714", not the decoy.
  5. Assert provenance where your runtime exposes it: write arguments trace to the lookup result, not to transcript text.
  6. Repeat with the context window under pressure: longer detours, a mid-call interruption, a resumed flow.

The decoy variant tends to surface what the happy-path trajectories miss: agents that pass every one of them still swap entities when a plausible wrong value appears closer to the write. If the write should also be refused for the wrong caller, that is an authorization case and belongs in the unauthorized action matrix.

The Assertion Table: One Row per Test Type

Test typeWhat to assertPass criteria
Tool selection (mocked)The expected tool was called; forbidden tools were notExpected mock called exactly once; forbidden mocks have empty call logs
Tool arguments (mocked)Write arguments field by field against the scripted scenarioEvery asserted field equals the fixture value; autospec raises no signature errors
Golden trajectorySequence, arguments, and terminal state for the branch takenTrace matches that branch's trajectory in the declared match mode; call ends in a defined end state
Branch coverageEach legitimate branch has its own trajectory testEvery branch classified and asserted; no call graded against a looser catch-all
Failure handlingProgrammed timeout or error on a dependencyAgent reports failure honestly; the retry re-sends the same write with the same idempotency key where the backend enforces one, and the replay-and-count check proves one durable result
ASR-to-schema alignmentSpoken dates, numbers, and amounts as typed argumentsArgument equals the expected normalized value for the scripted utterance
Context passingEarly verified context reaches late tool callsFinal write uses the verified value, not a late decoy or re-extraction
Transcript-trace agreementSpoken claims against the tool log, for caller-visible actionsEvery claimed action has a matching successful tool result, and every caller-visible action in the log was communicated; internal lookups are asserted as required or forbidden tool calls, not against the transcript

A workflow is covered when every row that applies to it has at least one case in CI, and the write-path rows block merge. How these gates fit a pipeline is covered in voice agent testing in CI/CD.

Where This Method Stops

Mock-based workflow tests prove the agent's behavior against a dependency you control. They do not prove the real integration works (that is the sandbox's job), that the workflow is safe against hostile callers (the authorization matrix's job), or that production calls keep matching the trajectories you wrote (monitoring's job, where traces from observability tooling feed failed calls back in as new regression cases). Treat this page as the method you repeat per workflow; the calendar booking guide shows one full repetition.

Frequently asked questions

Assert four layers: tool selection and arguments against mocked APIs, a golden trajectory per workflow branch (sequence, arguments, terminal state), schema-validated typed arguments for spoken entities, and context passing from early verification to late writes. A call passes when the trace matches the expected trajectory and terminal state with schema-valid arguments carrying verified context, and the transcript agrees with that trace, not when the conversation sounds right. With Hamming, these workflow failures are caught before launch and kept as permanent regression coverage.

Transcript testing grades what the agent said; tool-call testing grades what the tools actually did. The failures that matter live in the gap: an agent that claims success after a failed write, or fires a tool while verbally refusing. Assert both as separate witnesses and fail the test when they disagree.

Wrap the real client behind the agent's tools in a mock with programmed responses and a captured call log; in Python, unittest.mock's create_autospec enforces real signatures, side_effect scripts failures like timeouts, and call_args_list records every call for assertions. Then assert tool choice, call order, and arguments field by field against the scripted scenario. Use mocks for deterministic CI and move to sandboxes when the risk lives in real auth or schemas.

A golden trajectory is the expected tool-call path for one workflow written down before the call runs: the tool sequence, the arguments each write must carry, and the terminal state the workflow must end in. When a flow legitimately branches, each branch gets its own trajectory and forbidden-tool list rather than one looser match that accepts everything.

Script calls where the test knows exactly what the fixture caller said, then assert the typed tool argument equals the expected normalized value: ISO timestamp with offset, E.164 phone number, integer minor units for amounts. Schema validation at the tool boundary is the floor, because a schema-valid wrong date passes every type check. Test the ASR layer separately with real spoken digit strings and dates.

Script a scenario where the decisive value appears early, add a plausible decoy value late in the call, and assert the final write used the early verified value rather than the decoy or a re-extraction from conversation. Agents that pass happy-path trajectories still swap entities when a wrong value appears closer to the write, so run the decoy variant on every long workflow.