Skip to content

Module 08 · Lesson 8.2

Scenario-Based and End-to-End Agent Tests

45 minUpdated 18 Nov 2026Part of Testing and Evaluation · AI Agent Development
On this page
  1. What you will learn
  2. What a scenario test is and why it matters
  3. Scripted, recorded and live: three ways to run a scenario
  4. How record and replay works
  5. Example: replay recorded replies through a tiny agent loop
  6. Flaky results, repeat runs and keeping live tests few
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

A bike can pass every part check and still ride badly. The brakes work, the wheels spin and the chain is fine, yet the gears jump when you pedal hard. You only find that on a test ride, with all the parts working together.

Agents are the same. Unit tests check parts. A scenario test takes the whole agent for a ride: one realistic situation from the first message to the final answer. This lesson shows three ways to run such a test, what each one can catch, and how to handle results that change from run to run. Most of it needs no coding. The example replays recorded model replies through a tiny agent loop.

What you will learn

  • Explain what a scenario test is and how it differs from a unit test.
  • Choose between scripted, recorded and live model runs for a test.
  • Write a replay test that checks the final status and the tools called.
  • Handle flaky live results with repeat runs, and keep live tests few and labelled.

Before you start

What a scenario test is and why it matters

A scenario is one realistic situation, written down. It has a starting message, the steps the agent should take, and the result you expect. A scenario test runs the whole agent through it: the model, the tools, the safety gate, the loop and the final reply. Because it covers the full path, it is also called an end-to-end test.

Think of a fire drill. Checking that the alarm works is a unit test. Walking everyone out of the building is a scenario test. It shows whether the alarm, the doors and the people work together.

A scenario card

Write each scenario as a short card with a given, a when and a then. Here is one for the Quillfeather support agent:

Textscenario-01.txt
Name:   dispatched order
Given:  order QF-1042 is "dispatched"
When:   the customer writes "Where is QF-1042?"
Then:   the agent calls lookup_order once, with QF-1042
        and the final status is "answered"

Notice what the card checks. It checks the behaviour: which tool, and which status. It does not check the exact words of the reply, because those change between runs.

Scripted, recorded and live: three ways to run a scenario

The hard part of testing a whole agent is the model. It costs money, takes seconds and does not always answer the same way. You have three options.

Scripted fake
A stand-in for the model that you write by hand. It returns the replies you chose for this test, such as "call lookup_order", then "answer".
Recorded replies
Real model replies that you saved once and play back later. You record once and replay many times, like recording a TV show and watching it again.
Live run
A real call to a real model every time. It is the only option that shows what the model does today.
Scripted fakeRecorded replayLive run
SpeedInstantInstantSeconds per step
CostFreeFree after the recordingPays for model use each run
Same result every time?YesYesNo
Where the replies come fromYou invent themA real model, onceA real model, now
Catches bugs in your codeYesYesYes, but hard to pin down
Catches model or prompt problemsNoOnly those in the recordingYes
Goes stale when the prompt changesNoYes, needs a new recordingNo
Use the cheapest option that can catch the problem you care about.

What each one can catch

  • Scripted fakes catch mistakes in your loop: a missing step limit, a tool result that never reaches the model, a bad status that is not rejected.
  • Recorded replays catch the same mistakes, using replies that look like real ones. They also catch changes in how your code reads the model's output.
  • Live runs catch problems only a model can cause: choosing the wrong tool, ignoring an instruction or wandering off the task.

How record and replay works

Replay is the best everyday choice for end-to-end tests of your own code. It needs a little care.

  1. Step 1: Record once

    Run the scenario against the real model. Save every model reply, in order, to a file such as recordings/dispatched-order.json. JSON is a plain text format for structured data, so it is easy to read and to review.

  2. Step 2: Clean the recording

    Remove anything private, such as real names or emails, before you save. Keep made-up data in recordings. Never record secrets such as keys.

  3. Step 3: Replay many times

    In the test, a fake client hands back the saved replies one by one. Your tools and your loop run for real.

  4. Step 4: Check behaviour

    Assert the final status and the list of tools called. Do not assert the exact reply text.

  5. Step 5: Re-record on purpose

    When you change the instructions, a tool contract or the model, record again and look at the difference before you accept it.

Keep recordings in version control next to the tests, and name them after the scenario. A recording nobody can find is a recording nobody refreshes.

Example: replay recorded replies through a tiny agent loop

This example holds a very small agent loop and five scenarios. The "recorded replies" are written in a Python list here so the example stays short. In a real project you would load them from JSON files. Save the three parts below, in order, as replay_test.py.

Part 1: the tool and the loop

Pythonreplay_test.py
import re

ORDERS = {"QF-1042": "dispatched", "QF-1044": "delivered"}
STATUSES = ["answered", "needs_order_number", "return_requested", "needs_person", "not_found"]
MAX_ROUNDS = 3


def run_tool(name, args):
    order_id = args.get("order_id", "")
    if name != "lookup_order" or not re.fullmatch(r"QF-\d{4}", order_id):
        return {"error": "refused"}
    return {"status": ORDERS[order_id]} if order_id in ORDERS else {"error": "order not found"}


def run_agent(recorded_replies):
    """Replay recorded model replies through the loop. Return (status, tools called)."""
    tools_called = []
    for reply in recorded_replies[:MAX_ROUNDS]:
        if "call" in reply:
            tools_called.append(reply["call"])
            run_tool(reply["call"], reply["args"])
        elif reply["final"]["status"] in STATUSES:
            return reply["final"]["status"], tools_called
        else:
            return "needs_person", tools_called  # the contract check rejects an invented status
    return "needs_person", tools_called  # ran out of rounds

Part 1 of 3. The loop takes the recorded replies instead of calling a model.

Part 2: the scenarios

Pythonreplay_test.py
def call(order_id):
    return {"call": "lookup_order", "args": {"order_id": order_id}}


def final(status):
    return {"final": {"status": status, "reply": "..."}}


SCENARIOS = {
    "dispatched order": ([call("QF-1042"), final("answered")], "answered", ["lookup_order"]),
    "missing order number": ([final("needs_order_number")], "needs_order_number", []),
    "unknown order": ([call("QF-9999"), final("not_found")], "not_found", ["lookup_order"]),
    "model never stops": ([call("QF-1042")] * 5, "needs_person", ["lookup_order"] * 3),
    "invented status": ([final("maybe")], "needs_person", []),
}

Part 2 of 3. Add this below part 1. Each scenario holds replies, the expected status and the expected tools.

Part 3: the test runner

Pythonreplay_test.py
passed = 0
for name, (replies, want_status, want_tools) in SCENARIOS.items():
    status, tools = run_agent(replies)
    ok = status == want_status and tools == want_tools
    passed += ok
    print("PASS" if ok else "FAIL", "-", name)
print(f"{passed} of {len(SCENARIOS)} scenarios passed")

Part 3 of 3. Add this at the bottom. Run it with python replay_test.py.

What each part does

  • ORDERS and STATUSES are made-up shop data and the five allowed reply statuses from the reply contract.
  • MAX_ROUNDS = 3 is the step limit. The loop never looks at more than three replies.
  • run_tool is a tiny safety gate: only lookup_order is allowed, and only with an order id like QF-1234. Anything else gets {"error": "refused"}.
  • run_agent(recorded_replies) is the loop. A reply with a "call" key is a tool call, so the loop runs the tool and writes its name in tools_called. A reply with a "final" key ends the run.
  • The else branch rejects a status that is not on the allowed list, so an invented status becomes needs_person instead of reaching a customer.
  • The last return runs when the model used up its rounds without finishing. The result is again needs_person.
  • call(...) and final(...) are short helpers that build recorded replies, so the scenarios stay readable.
  • Each entry in SCENARIOS is a name, the recorded replies, the expected status and the expected list of tools.
  • The runner replays every scenario, compares both results with ==, and prints PASS or FAIL. passed += ok counts a passing scenario, because True counts as 1.
Output of python replay_test.pyCaptured from a real run
PASS - dispatched order
PASS - missing order number
PASS - unknown order
PASS - model never stops
PASS - invented status
5 of 5 scenarios passed

Break it on purpose

A test you have never seen fail is a test you cannot trust. Change MAX_ROUNDS = 3 to MAX_ROUNDS = 10 and run the file again. The "model never stops" scenario now lets the loop run longer than the limit, so its tool list no longer matches:

Output with MAX_ROUNDS = 10Captured from a real run
PASS - dispatched order
PASS - missing order number
PASS - unknown order
FAIL - model never stops
PASS - invented status
4 of 5 scenarios passed

The scenario caught a change to the step limit that no unit test of run_tool would have noticed. Change the value back to 3 before you move on.

Flaky results, repeat runs and keeping live tests few

A flaky test sometimes passes and sometimes fails, with no change to the code. With live models, flakiness is normal. The model may call the right tool on Monday and an extra one on Tuesday. A flaky test is not useless, but it must be read differently.

Rules for live scenario tests

  • Keep them few. Five to ten live scenarios for your most important paths is a good start. Each one costs money and time.
  • Label them. Put the word live in the test name or file name, and run them on their own command. Nobody should pay for a model call by accident.
  • Run each one several times. Five runs is a common choice. Record how many passed, for example 4 of 5.
  • Decide the pass rule in advance. For example: a safety scenario must pass 5 of 5, an everyday scenario at least 4 of 5.
  • Look at failures. A failed run tells you something. Read it before you rerun it. Do not simply run it again until it passes.
  • Never block a code change on one flaky live run. Block on the deterministic tests, and review the live ones.
Kind of testHow often to runBlocks a release?
Unit testsEvery save and every commitYes
Replay scenariosEvery commitYes
Live scenarios, repeatedBefore a release, and after a model or prompt changeReview the results by rule
Fast and certain tests run often. Slow and uncertain tests run when it matters.

A live result is a sample, not a fact. Say "it passed 4 of 5 runs on that day with that model" rather than "it works". The lesson Measuring Accuracy, Task Completion and Tool Selection explains why small samples can mislead.

Conclusion and your next step

A scenario test takes the whole agent for a ride. Scripted fakes and recorded replies make it fast, free and repeatable, and they test your own code. Live runs show what the model does, but they are slow, costly and uneven, so keep them few, label them and repeat them. Check behaviour such as the final status and the tools called. Do not check exact words.

Your next step: write three scenario cards for your own agent, one normal, one that should end in a handover, and one with a bad input. Then continue to Evaluation Datasets, Rubrics and Expected Behaviours, where you collect many such cases into one dataset.

For related reading, see Human-in-the-Loop Approval and Escalation, which has handover cases worth turning into scenarios, or the Tool-Calling Loop: Reference Diagram.

Common errors and how to fix them

A replay test keeps passing even though the live agent got worse.

Why it happens: The recording is old. It replays replies from an earlier prompt or model.

Fix: Re-record after any change to instructions, tools or model, and review what changed.

A scenario test fails every time the model rewords its answer.

Why it happens: The test compares the exact reply text.

Fix: Check the final status and the tools called. Use a small set of required words if you must check the text.

The test bill grows every week.

Why it happens: Live-model tests run on every commit.

Fix: Use replay for everyday runs. Run live tests on a separate command, before releases.

A recording contains a real customer's email.

Why it happens: A live run was saved without cleaning it.

Fix: Clean recordings before saving. Use made-up data for recorded runs.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Add two scenarios to the replay test

Extend replay_test.py with two new scenarios, then run it and confirm that all seven scenarios pass.

You will need

  • Scenario one, forbidden tool: the model asks to call a tool named delete_order with the order id QF-1042, then gives a final reply with the status needs_person.
  • Scenario two, short order id: the model calls lookup_order with the order id QF-12, then gives a final reply with the status not_found.
  • The list of tools called records every call the model tried, even a refused one.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Use the helper call("QF-12") for the second scenario. For the first, write the call as a dictionary with a "call" key and an "args" key, because call(...) always uses lookup_order.
  • Look at how the existing entries are written and copy their shape.
  • The gate refuses both calls, so the loop carries on to the final reply.
Show a model answer

Add two entries to SCENARIOS. The first is "forbidden tool": ([{"call": "delete_order", "args": {"order_id": "QF-1042"}}, final("needs_person")], "needs_person", ["delete_order"]). The second is "short order id": ([call("QF-12"), final("not_found")], "not_found", ["lookup_order"]). In both cases run_tool returns the refusal, the loop moves on to the final reply, and the tool list shows what the model tried. These two scenarios are worth keeping because they prove the gate blocks a tool that should not exist and an order id of the wrong shape, even when the model asks for them.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.When is a recorded replay the better choice than a live run?
    Show the answer and explanation

    Answer: B. A replay gives the same result every time and costs nothing, so it suits tests of your own code. A replay cannot show how a model reacts to a new prompt, which makes the third option tempting but wrong. The recording is of the old prompt.

  2. 2.What should a scenario test usually check?
    Show the answer and explanation

    Answer: B. Status and tool calls are behaviour, and they stay stable when the wording changes. Exact words are tempting because they are easy to compare, but they make the test fail whenever the model rewords a correct answer.

  3. 3.A live scenario passed 3 of 5 runs. What is the sensible reaction?
    Show the answer and explanation

    Answer: B. Failures hold the information. Rerunning until green hides a real problem, and deleting the scenario throws away the signal. Flaky results are normal with live models, so the answer is to read them against a rule.

Frequently asked questions

What is the difference between a unit test and an end-to-end test?

A unit test checks one small piece of code, such as a tool. An end-to-end test runs the whole path, from the customer's first message to the final reply. Unit tests find faults quickly and exactly. End-to-end tests find faults that only appear when the parts work together.

How do I test an AI agent without paying for the model every time?

Replace the model with a fake that returns scripted replies, or with recorded replies from one earlier real run. Your tools and your loop still run for real. Keep a small number of live tests for before a release.

Why does my agent test pass sometimes and fail other times?

With a live model, the answer can change from run to run, so the test is flaky. Run it several times and look at the rate, for example 4 of 5. If the test must be steady, use a scripted fake or a recording instead.

How many scenarios should I write?

Start with about ten: the normal cases, a few that should end in a handover and a few with bad or unsafe input. Add one more every time you find a real bug. Later lessons show how to grow this into a larger evaluation dataset.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.