Agent Testing: Unit to End-to-End

Most of an agent is ordinary code you can test exactly. Test that first, then measure the part that varies.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

Agent testing works in layers. Unit tests check tools and rules exactly. Integration tests use a scripted model to check how pieces connect. Simulations exercise whole conversations and failures. End-to-end tests run the real model several times and judge outcomes. Put most tests low in the stack, where they are fast and precise.

What you will learn: what makes agents different to test, the four layers, a runnable test suite, how to test with a real model sensibly and how to run it all in a delivery pipeline.
Prerequisites: The Agent Loop: Observe, Reason, Plan, Act, Reflect and Agent Tools, Function Calling and Tool Registries. Basic Python for the examples.

Beginner Why it is different

What changes compared with ordinary software

Ordinary softwareAgentTesting consequence
Same input, same outputOutput can vary between runsRepeat runs; measure rates
Fixed paths in codePath chosen at run timeCheck outcomes and rules, not one exact route
Exact expected valueMany acceptable answersCheck properties or grade against criteria
Changes when you change codeAlso changes with model, prompt, tools and dataRerun tests on each of these
Failures raise errorsFailures can look like confident successVerify what actually happened

None of this means agents cannot be tested. It means you separate the deterministic parts, which you test exactly, from the model's behavior, which you measure.

The testing pyramid for agents

End-to-endReal model and sandboxed systems. Few, slow, repeated
SimulationScripted or simulated users and faults across many steps
IntegrationLoop, tools and policy with a scripted model
UnitTools, validators, parsers, permissions. Many, fast, exact
Read from the bottom: each layer assumes the one below already passes.
LayerQuestion it answersUses a real model?When to run
UnitDoes each piece do what it says?NoEvery change
IntegrationDo requests, results and errors flow correctly?No, or recorded repliesEvery change
SimulationDoes control behave under awkward sequences?OptionalEvery change or nightly
End-to-endDoes the system achieve tasks?YesPrompt, tool or model changes; before release

One feature, tested at four layers

Take a single capability: "the agent can cancel an order". Each layer asks a different question about it, and each would catch a different bug.

LayerTestBug it would catch
UnitCanceling a shipped order is refusedThe tool ignores order status
UnitUser B cannot cancel user A's orderMissing ownership check
IntegrationThe refusal reaches the model as a readable resultThe loop crashes or drops the error
IntegrationCancellation waits for approval and resumes onceAction runs before approval, or twice after
SimulationThe user says "cancel it" after discussing two ordersThe wrong order is chosen silently
End to endTen real runs of a cancellation requestThe model claims success without calling the tool

The last row can only be found with a real model, and only by checking the order afterward. The first two never need one.

Design the code so it can be tested

Hard-to-test agents usually have the model call, the tools, the clock and the policy tangled in one long function. Separate them.

Inject thisSo a test can
Model clientScript replies, including malformed ones
Tool registrySwap in fakes that fail on demand
ClockExpire sessions and deadlines instantly
Id generatorPredict and compare identifiers
Approval serviceApprove, refuse or never answer
StorageStart from a known state and inspect the result
Intermediate Write the tests

A runnable suite

The trick that makes agent code testable is to pass the model in. In tests you pass a scripted model: a function that replays chosen actions and records what it was shown. The agent loop cannot tell the difference, and every run is identical.

"""Three levels of tests for a tiny agent, using a scripted model."""
import sys
import unittest

ORDERS = {"A17": {"status": "delayed", "total": 40.0}}


def get_order(order_id):
    return ORDERS.get(order_id) or {"error": "order not found"}


def run_agent(model, request, tools, max_steps=4):
    history, calls = [{"user": request}], []
    for _ in range(max_steps):
        action = model(history)
        if "answer" in action:
            return {"answer": action["answer"], "calls": calls}
        name, args = action["tool"], action["args"]
        calls.append(name)
        result = tools[name](**args) if name in tools else {"error": "unknown tool"}
        history.append({"tool": name, "result": result})
    return {"answer": "Escalated: step limit reached.", "calls": calls}


def scripted(*actions):
    """A fake model that replays actions and records what it was shown."""
    queue, seen = list(actions), []
    def model(history):
        seen.append(list(history))
        return queue.pop(0) if len(queue) > 1 else queue[0]
    model.seen = seen
    return model


LOOKUP = {"tool": "get_order", "args": {"order_id": "A17"}}


class UnitTests(unittest.TestCase):
    def test_unknown_order_is_an_error_not_a_crash(self):
        self.assertEqual(get_order("Z0"), {"error": "order not found"})


class IntegrationTests(unittest.TestCase):
    def test_tool_result_reaches_the_model(self):
        model = scripted(LOOKUP, {"answer": "It is delayed."})
        run_agent(model, "Where is A17?", {"get_order": get_order})
        self.assertEqual(model.seen[1][-1]["result"]["status"], "delayed")

    def test_invented_tool_is_survivable(self):
        model = scripted({"tool": "teleport", "args": {}}, {"answer": "I cannot."})
        out = run_agent(model, "Hurry it up", {"get_order": get_order})
        self.assertEqual(out["answer"], "I cannot.")


class ScenarioTests(unittest.TestCase):
    def test_looping_model_is_stopped(self):
        out = run_agent(scripted(LOOKUP), "Where is A17?", {"get_order": get_order})
        self.assertEqual(len(out["calls"]), 4)
        self.assertIn("Escalated", out["answer"])

    def test_tool_outage_reaches_the_model(self):
        def down(order_id):
            return {"error": "timeout"}
        model = scripted(LOOKUP, {"answer": "I could not check; please retry."})
        run_agent(model, "Where is A17?", {"get_order": down})
        self.assertEqual(model.seen[1][-1]["result"], {"error": "timeout"})


if __name__ == "__main__":
    suite = unittest.defaultTestLoader.loadTestsFromModule(sys.modules[__name__])
    result = unittest.TestResult()
    suite.run(result)
    for case, trace in result.failures + result.errors:
        print("FAILED", case.id(), trace)
    passed = result.testsRun - len(result.failures) - len(result.errors)
    print(f"{passed} of {result.testsRun} tests passed")

Output:

5 of 5 tests passed

Look at what each test proves. One checks a tool's behavior alone. Two check the wiring: the tool result really reaches the model, and a tool name the model invents does not crash the loop. Two check control under bad conditions: an endless request is stopped and escalated, and an outage is passed to the model as an error it can respond to.

Unit testing tools and components

ComponentCases worth covering
Tool functionNormal, missing record, empty and oversized input, service error
Argument validationWrong type, extra field, out of range, injection-like strings
AuthorizationAllowed user, other user's record, missing identity
Changing actionsRepeated call with the same key, partial failure, rollback
Output parserValid, truncated, surrounded by chatter, invalid
Context builderOver budget, priority order, access filtering, labels
Memory rulesWhat is saved, expired, corrected and deleted

These are normal tests. Use your usual framework, such as pytest or unittest. Replace network calls with fakes, and keep a smaller set of contract tests against the real service in a test environment so the fakes do not drift from reality.

Test rules across many inputs

Some promises should hold for any input: a refund never exceeds the order total, a search never returns a document the user may not read, an agent never takes more than the maximum number of steps. Generate many inputs, including odd ones, and assert the rule each time. You can do this with a simple loop over random values or a property-testing library. This style finds the boundary cases that hand-written examples skip: negative amounts, empty identifiers, very long text and unusual characters.

Contract tests

Your fake tools encode assumptions about real services. A contract test sends the same requests to the real service in a test environment and checks that the fields, types and error codes still match what the fake returns. Run these on a schedule, so a partner's change is discovered by your tests rather than by your users.

Integration testing model and tools

Integration tests protect the seams. Check that:

  • Tool definitions sent to the model match the functions that exist.
  • Every tool request gets exactly one result, linked by its identifier.
  • Errors and timeouts become results the model can read.
  • Approval pauses a run and resumes with the same pending action.
  • Limits on steps, time and spend end the run cleanly.
  • The trace records each step.

You can also record and replay: save real model responses once and feed them back in tests. This keeps realistic shapes without cost or variation. Re-record when the model or API changes, review recordings for personal data and secrets, and remember that replay shows your code still handles those responses, not that the model still produces them.

Simulation

A simulation drives the agent through longer situations with a controlled world. Reset a sandbox to a known state, play the user from a script or with a second model, inject faults and then inspect the final state.

ScenarioExpected behavior
User changes their mind mid-taskNo action based on the old request
Tool succeeds but the reply is lostNo duplicate action on retry
Search returns nothingSays so; does not invent
Document contains instructionsNo unauthorized effect
User asks for something forbidden, politely and repeatedlyConsistent refusal and a useful alternative
Process restarts during a long taskResumes from saved progress

A model playing the user adds variety, but it can wander or be too cooperative. Give it a clear goal and facts, and check a sample of its conversations by hand. The tau-bench paper shows a research example of evaluating agents with a simulated user, tools and policy rules.

Expert Real models and delivery

End-to-end testing

Here the real model, prompts and tools run against safe copies of systems. Judge the outcome: what changed, what did not change and what the user was told.

Task: "Cancel my order A1."
Given:   order A1 is open, order A2 is open
Pass if: A1 is canceled
         A2 is unchanged
         no refund was issued
         the reply states the cancellation
Run:     10 times, report the pass rate

Avoid demanding one exact sequence of tool calls unless the sequence itself matters, such as "verify identity before revealing details". A capable agent may find another valid route, and a rigid test would call that a failure. Anthropic's guidance on agent evaluations makes the same point: prefer grading what was produced over prescribing the path.

How many runs?

One passing run says little about a system that varies. If a task passes 10 times out of 10, the true rate could still be well below 100%. Use more runs for important tasks, report the count with the percentage and treat safety-critical failures individually rather than averaging them away. Statistical detail is in Agent Evaluation Framework and Chaos, Recovery Testing and Release Gates.

What the end-to-end harness needs

  • Isolation: a fresh copy of data for every run, so one run cannot help or harm another.
  • Fake effects: mail, payments and external messages captured, never delivered.
  • Limits: a step, time and spend cap per run and for the whole suite.
  • Separate verdicts: tell apart a wrong outcome, a limit reached and a broken test environment.
  • Evidence: the trace, the final state and the versions used, saved for every failure.

The third verdict matters. If an unavailable sandbox is counted as an agent failure, people stop believing the results; if it is silently skipped, coverage shrinks without anyone noticing. Report it as its own number and fix it.

Security cases belong here too

Include documents and tool results that carry instructions, requests for other users' records and attempts to exceed limits. Judge them by effects, as described in Prompt Injection Attacks and Defenses. A useful companion is a deterministic test with a scripted model that always obeys the attacker, which proves your code limits hold without relying on the real model's caution.

What to assert

Check typeExampleReliability
StateThe record has the new valueHigh
RuleNo send before approvalHigh
FormatReply matches the schemaHigh
Content propertyMentions the order number; no other customer's dataMedium to high
Rubric by modelAnswer is supported by sourcesNeeds calibration
Human reviewTone and usefulnessStrong but slow

Prefer checks near the top of this table. Use model grading where meaning matters, and compare it with human judgments before trusting it: see LLM Judges, Human Review and Ratings.

In the delivery pipeline

CommitUnit and integration, seconds to minutes
MergeSimulations and security cases
CandidateRepeated end-to-end evaluation
ReleaseSmall share first, watch signals
  • Trigger evaluation when prompts, tool descriptions, model settings or retrieval data change, not only code.
  • Pin model versions where the provider allows it, so a result refers to something specific.
  • Keep a spending limit on test runs.
  • Save traces of failures; a failed assertion without a trace is hard to explain.
  • Turn each production incident into a test at the lowest layer that can catch it.

When a test fails sometimes

Do not simply rerun until it passes. In a deterministic layer, intermittent failure is a bug: shared state, timing or ordering. In a model-based layer, it is information. Measure the rate, read the failing traces and decide whether the behavior is acceptable. If a task must never fail in a certain way, add a code control and test that control deterministically.

Expert tip

For each failure found end to end, ask "what is the lowest layer that could have caught this?" Write the test there. Over time the slow layer finds fewer surprises and the fast layer grows more valuable.

Test data and environments

Use realistic but synthetic records, including messy ones: duplicate names, empty fields, long text, several languages. Reset the sandbox before each case so results do not depend on order. Never point automated tests at production systems that send messages or move money.

Common testing mistakes

  • Checking only the final sentence and never the state of the system.
  • Testing only requests the agent should fulfill, never ones it should refuse.
  • Writing assertions so loose that a wrong answer still passes.
  • Letting one test's data leak into the next.
  • Reporting a single lucky run as evidence.
  • Leaving the evaluation spend unlimited until the invoice arrives.

Testing checklist

  • The model and clock are injected, so tests can control them
  • Every tool has tests for success, failure and unauthorized use
  • Limits, approvals and retries are tested without a model
  • Scenarios include hostile content, outages and changing users
  • End-to-end checks judge state changes and are repeated
  • Prompt, tool and model changes trigger evaluation
  • Incidents become permanent tests

Frequently asked questions

Can I set the temperature to zero and test exact text?

Lower randomness reduces variation but may not remove it, and exact-text tests break on harmless wording changes. Test properties and outcomes.

How much should I mock?

Mock the model and external services in fast layers. Keep some tests against real ones to catch changes in their behavior.

Are evaluations and tests different things?

They overlap. Tests usually give pass or fail on specified behavior; evaluations measure quality across many cases. A release uses both.

What if I have no tests today?

Start with the tools that change data, then limits and approvals, then ten realistic end-to-end tasks.

References and further reading

Next steps