# Agent Framework tests and pass rates in C# with Claude

> Source: <https://dev.to/nkootstra/agent-framework-tests-and-pass-rates-in-c-with-claude-4d94>
> Published: 2026-11-24 18:38:53+00:00

**Recommendation:** Split agent behavior into code-decided and model-decided parts: unit-test the former, stub IChatClient for the middle layer, and run real scenarios ten times to get pass rates and per-scenario cost.
More in the playbook "Evals and testing for LLM apps": <https://wpnews.pro/playbooks/evals-testing>

**The idea:** what code decides gets an ordinary test that passes or fails. What the model decides gets the same scenario run several times, a check on what the agent did, and a pass rate as the result.

A kitchen assistant that keeps a shopping list makes two kinds of decisions. Some are made by code: the list stores items in lower case, refuses anything with "peanut" in its name and never holds the same item twice. Those behave the same on every run, and a unit test proves them. The others are made by the model: whether "Do we have eggs?" is a question or a request to buy eggs, and which ingredients a recipe still needs. Those can differ between two runs of the same request. This post tests the assistant in three layers: the code on its own, the agent with a scripted model in place of Claude, and real scenarios against Claude Haiku 5.5, each run ten times, with a pass rate and a cost per scenario.

**Versions:** Microsoft Agent Framework 1.24.0, .NET 10, xUnit v3 4.0.1 (`xunit.v3.mtp-v2`), NSubstitute 6.2.0.

**Code:** [samples/agent-framework/14-testing-agents](https://github.com/nkootstra/samples/tree/main/agent-framework/14-testing-agents), a runnable version of this post with its tests.

**Who this is for:** C# developers who have an agent with tools, as in [Agent Framework tool calling in C# with Claude](https://kootstra.io/writing/tool-calling-ai-agents-csharp/).

**Note**

The code runs on Claude Haiku 5.5, but it depends only on `IChatClient`: [the first post](https://kootstra.io/writing/microsoft-agent-framework-first-csharp-agent/#swap-the-provider-by-changing-one-statement) shows the swap to OpenAI or Ollama.

The costs use Haiku's list prices, which are constants in the test code; another model needs its own. The output limit of 4,096 tokens is sized for Haiku, which counts its reasoning as output.

A console app with the two Agent Framework packages:

```
dotnet new console -n KitchenScenarios
cd KitchenScenarios
dotnet add package Microsoft.Agents.AI --version 1.24.0
dotnet add package Microsoft.Agents.AI.Anthropic --version 1.24.0
```

The household's kitchen is one class, in `Kitchen.cs`, with a pantry to read and a shopping list to write:

```
using System.ComponentModel;

sealed class Kitchen
{
    readonly Dictionary<string, string> _pantry =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["rice"] = "1 kg",
            ["eggs"] = "6",
            ["onions"] = "3",
            ["spinach"] = "200 g",
            ["feta"] = "150 g",
        };

    readonly List<string> _shoppingList = [];

    public IReadOnlyList<string> ShoppingList => _shoppingList;

    [Description("Looks up one ingredient in the household's pantry.")]
    public string FindInPantry(
        [Description(
            "One ingredient as a plain noun, for example eggs.")]
        string ingredient)
    {
        if (_pantry.TryGetValue(ingredient, out string? amount))
        {
            return $"{ingredient}: {amount}.";
        }

        return $"No {ingredient} in the pantry. " +
            $"The pantry has: {string.Join(", ", _pantry.Keys)}.";
    }

    [Description("Adds one item to the household's shopping list.")]
    public string AddToShoppingList(
        [Description("One item as a plain noun, for example milk.")]
        string item)
    {
        string name = item.Trim().ToLowerInvariant();

        if (name.Length == 0)
        {
            return "Not added: the item is empty. " +
                "Name one item, for example milk.";
        }

        if (name.Contains("peanut", StringComparison.Ordinal))
        {
            return $"Not added: {name}. " +
                "Nobody in this household eats peanuts.";
        }

        if (_shoppingList.Contains(name))
        {
            return $"{name} is already on the shopping list.";
        }

        _shoppingList.Add(name);
        return $"Added {name}. " +
            $"The list now has: {string.Join(", ", _shoppingList)}.";
    }
}
```

The peanut rule is in the tool, not in the instructions. Whatever the model asks for, `AddToShoppingList` decides whether an item goes on the list, so the rule holds on every run and a unit test can prove it.

The agent is built in `KitchenAgent.cs`, so the app and the tests create it the same way:

```
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

static class KitchenAgent
{
    public static AIAgent Create(IChatClient chatClient, Kitchen kitchen) =>
        chatClient.AsAIAgent(
            name: "kitchen-assistant",
            instructions: """
                You help one household with its pantry and shopping list.
                Check the pantry with your tools before you answer.
                Only add items to the shopping list when the household asks for it.
                Answer in one short sentence.
                """,
            tools:
            [
                AIFunctionFactory.Create(
                    kitchen.FindInPantry, name: "find_in_pantry"),
                AIFunctionFactory.Create(
                    kitchen.AddToShoppingList, name: "add_to_shopping_list"),
            ]);
}
```

`Create` takes the `IChatClient` and the `Kitchen` as parameters. The app passes Claude and a real kitchen; a test passes a scripted chat client and a kitchen it can inspect afterwards.

The tests go in a second project next to the app, with xUnit v3 and [NSubstitute](https://nsubstitute.github.io/) for the stubs in layer 2:

```
cd ..
dotnet new console -n KitchenScenarios.Tests
cd KitchenScenarios.Tests
rm Program.cs
dotnet add package xunit.v3.mtp-v2 --version 4.0.1
dotnet add package NSubstitute --version 6.2.0
dotnet add reference ../KitchenScenarios
```

An xUnit v3 test project is a console app whose entry point xUnit generates, so the template's `Program.cs` goes. Two project files need one item each. The test project imports the `Xunit` namespace in every file:

```
<ItemGroup>
  <Using Include="Xunit" />
</ItemGroup>
```

The app's classes have no access modifier, so they are `internal`, and the app's project file makes them visible to the tests:

```
<ItemGroup>
  <InternalsVisibleTo Include="KitchenScenarios.Tests" />
</ItemGroup>
```

`xunit.v3.mtp-v2` runs on Microsoft.Testing.Platform. On .NET 10, `dotnet test` refuses such a project ("Testing with VSTest target is no longer supported by Microsoft.Testing.Platform on .NET 10 SDK and later") unless a `global.json` above it switches the runner:

```
{
  "test": {
    "runner": "Microsoft.Testing.Platform"
  }
}
```

`Kitchen` knows nothing about agents, so its tests don't either. They call the methods directly, as the model's requests would, and check the result and the list:

```
public sealed class KitchenTests
{
    readonly Kitchen _kitchen = new();

    [Fact]
    public void An_item_already_on_the_list_is_not_added_twice()
    {
        _kitchen.AddToShoppingList("milk");

        string result = _kitchen.AddToShoppingList("MILK");

        Assert.Equal(["milk"], _kitchen.ShoppingList);
        Assert.Equal("milk is already on the shopping list.", result);
    }

    [Theory]
    [InlineData("peanut butter")]
    [InlineData("Salted Peanuts")]
    public void Anything_with_peanuts_is_refused_with_the_reason(string item)
    {
        string result = _kitchen.AddToShoppingList(item);

        Assert.Empty(_kitchen.ShoppingList);
        Assert.StartsWith("Not added: ", result);
        Assert.EndsWith("Nobody in this household eats peanuts.", result);
    }
}
```

These tests run in milliseconds, cost nothing and give the same answer every time. Every rule moved out of the instructions and into a tool gains a test like this. "Nobody eats peanuts" as a line in the instructions is a request the model usually follows. In `AddToShoppingList` it is a rule with a test.

The second layer checks that the agent is put together correctly: the model gets both tools and the instructions, a tool call from the model reaches the kitchen, and the result goes back. Claude is replaced by an NSubstitute stub of `IChatClient` that returns scripted responses. The first response asks for a tool call, the second is the answer:

```
public sealed class KitchenAgentTests
{
    readonly IChatClient _chatClient = Substitute.For<IChatClient>();
    readonly List<ChatOptions?> _sentOptions = [];
    readonly List<ChatMessage[]> _sentMessages = [];

    // The model asks for one tool call, then answers.
    void ModelCalls(string tool, string parameter, string argument) =>
        _chatClient
            .GetResponseAsync(
                Arg.Do<IEnumerable<ChatMessage>>(sent => _sentMessages.Add([.. sent])),
                Arg.Do<ChatOptions?>(_sentOptions.Add),
                Arg.Any<CancellationToken>())
            .Returns(
                new ChatResponse(new ChatMessage(
                    ChatRole.Assistant,
                    [
                        new FunctionCallContent(
                            "call-1",
                            tool,
                            new Dictionary<string, object?> { [parameter] = argument }),
                    ])),
                new ChatResponse(new ChatMessage(ChatRole.Assistant, "Done.")));

    Task<AgentResponse> RunAsync(Kitchen kitchen, string message) =>
        KitchenAgent.Create(_chatClient, kitchen).RunAsync(
            message,
            cancellationToken: TestContext.Current.CancellationToken);

    [Fact]
    public async Task An_add_call_from_the_model_lands_on_the_kitchens_list()
    {
        ModelCalls("add_to_shopping_list", "item", "milk");
        var kitchen = new Kitchen();

        await RunAsync(kitchen, "We're out of milk.");

        Assert.Equal(["milk"], kitchen.ShoppingList);
    }

    [Fact]
    public async Task The_model_gets_both_tools_by_name()
    {
        ModelCalls("find_in_pantry", "ingredient", "eggs");

        await RunAsync(new Kitchen(), "Do we have eggs?");

        Assert.Equal(
            ["find_in_pantry", "add_to_shopping_list"],
            _sentOptions[0]!.Tools!.Select(t => t.Name));
    }
}
```

Only the model is replaced. Everything between the stub and the kitchen is the real Agent Framework and Microsoft.Extensions.AI code: `ChatClientAgent` adds a `FunctionInvokingChatClient` to the stub's pipeline, so the scripted `FunctionCallContent` is run as a real tool call. The agent's instructions reach the chat client in `ChatOptions.Instructions`, which is where the sample's instructions test reads them.

These tests prove that the agent can use its tools. They say nothing about whether Claude will. The stub calls `add_to_shopping_list` because the test told it to. Whether Claude adds milk when someone says "we're out of milk" is a property of the model, the instructions and the tool descriptions together, and the only way to measure it is to ask Claude.

A scenario is a request and a check. The check looks at what the agent did, the tool calls in the response and the shopping list afterwards, and never at the wording of the answer. "Milk is on your list" and "I've added milk" are both right; a list that holds milk is the fact that matters. In `Scenario.cs`:

```
using Microsoft.Extensions.AI;

// A check returns null when the run passed, or what went wrong.
sealed record Scenario(
    string Name,
    string Prompt,
    Func<ScenarioRun, string?> Check);

sealed record ScenarioRun(
    IReadOnlyList<FunctionCallContent> Calls,
    IReadOnlyList<string> ShoppingList);
```

Four scenarios, in `Scenarios.cs`, cover the decisions the model makes for this kitchen:

```
static class Scenarios
{
    static readonly string[] Pasta =
    [
        "pasta", "spaghetti", "penne", "fusilli", "linguine",
        "tagliatelle", "fettuccine", "pappardelle", "rigatoni",
        "farfalle", "macaroni", "orzo", "orecchiette", "conchiglie",
    ];
    static readonly string[] InThePantry =
        ["rice", "egg", "eggs", "onion", "onions", "spinach", "feta"];

    public static readonly Scenario[] All =
    [
        new("milk on the list",
            "We're out of milk. Put it on the shopping list.",
            run => run.ShoppingList is [var item]
                && HasWord(item, "milk")
                    ? null
                    : "expected milk and nothing else"),

        new("question only",
            "Do we have eggs?",
            run => !run.Calls.Any(c => c.Name == "find_in_pantry")
                ? "never checked the pantry"
                : run.ShoppingList.Count > 0
                    ? "added to the list without being asked"
                    : null),

        new("no peanuts",
            "Put peanut butter on the shopping list.",
            run => run.ShoppingList.Count == 0
                ? null
                : "added something nobody asked for"),

        new("missing for a recipe",
            "I want to cook pasta with spinach and feta tonight. "
                + "Add what I'm missing to the shopping list.",
            run => !run.ShoppingList.Any(name => HasWord(name, Pasta))
                ? "no pasta on the list"
                : run.ShoppingList
                    .FirstOrDefault(name => HasWord(name, InThePantry))
                    is { } item
                    ? $"{item} is already in the pantry"
                    : null),
    ];

    // Whole words, any case: "eggplant" is not "egg", "Penne" is "penne".
    static bool HasWord(string item, params string[] words) =>
        item.Split([' ', '-'], StringSplitOptions.RemoveEmptyEntries)
            .Any(word => words.Contains(word, StringComparer.OrdinalIgnoreCase));
}
```

"question only" checks a tool call: an answer about eggs that didn't come from `find_in_pantry` was made up, even when it happens to be right. "no peanuts" can't fail through peanut butter, because the tool refuses it. It fails if the model adds something in its place, almond butter for example, which nobody asked for. "missing for a recipe" allows extras such as garlic and olive oil, and fails when no item names a pasta from `Pasta` or an item names something from `InThePantry`.

A check that rejects a right answer reports a failure the model didn't make, so the word list is a judgement call: it has to hold the answers the model is likely to give. It accepts the common shapes and still misses lasagne and ravioli. If `Pasta` held only the word "pasta", a run that put tagliatelle on the list would fail while doing what the household asked. `HasWord` compares whole words and ignores case for the same reason: with a plain `Contains`, "eggplant" would count as eggs from the pantry and "buttermilk" as milk. The checks are code, so they get layer 1 tests of their own:

```
[Fact]
public void Any_kind_of_pasta_and_extras_pass()
{
    Assert.Null(Check("missing for a recipe", ["spaghetti", "garlic"], "add_to_shopping_list"));
}

[Theory]
[InlineData("tagliatelle")]
[InlineData("orzo")]
[InlineData("macaroni")]
[InlineData("Rigatoni")]
[InlineData("whole-wheat penne")]
public void Common_pasta_shapes_count_as_pasta(string pasta)
{
    Assert.Null(Check("missing for a recipe", [pasta], "add_to_shopping_list"));
}

[Fact]
public void An_item_that_only_contains_a_pantry_word_is_not_in_the_pantry()
{
    Assert.Null(Check("missing for a recipe", ["penne", "eggplant"], "add_to_shopping_list"));
}

[Fact]
public void Buying_what_the_pantry_already_has_fails()
{
    Assert.Equal(
        "feta is already in the pantry",
        Check("missing for a recipe", ["pasta", "feta"], "add_to_shopping_list"));
}
```

`Check` here is a small helper in the test class that looks up the scenario by name and runs its check on a made-up list and the names of the calls.

The runner needs no framework. It runs one scenario a given number of times, each time with a new `Kitchen` and a new agent, and counts the runs whose check returns `null`. It goes in `ScenarioRunner.cs`:

```
using Microsoft.Agents.AI;
using Microsoft.Extensions.AI;

sealed record ScenarioResult(
    string Name,
    int Passed,
    int Runs,
    long InputTokens,
    long OutputTokens,
    List<string> Failures);

static class ScenarioRunner
{
    public static async Task<ScenarioResult> RunAsync(
        IChatClient chatClient,
        Scenario scenario,
        int runs,
        CancellationToken cancellationToken = default)
    {
        int passed = 0;
        long inputTokens = 0, outputTokens = 0;
        List<string> failures = [];

        for (int run = 1; run <= runs; run++)
        {
            var kitchen = new Kitchen();
            AIAgent agent = KitchenAgent.Create(chatClient, kitchen);

            AgentResponse response = await agent.RunAsync(
                scenario.Prompt, cancellationToken: cancellationToken);

            inputTokens += response.Usage?.InputTokenCount ?? 0;
            outputTokens += response.Usage?.OutputTokenCount ?? 0;

            List<FunctionCallContent> calls = response.Messages
                .SelectMany(m => m.Contents)
                .OfType<FunctionCallContent>()
                .ToList();

            string? problem = response.FinishReason == ChatFinishReason.Stop
                ? scenario.Check(new ScenarioRun(calls, kitchen.ShoppingList))
                : $"finish: {response.FinishReason}";

            if (problem is null)
            {
                passed++;
            }
            else
            {
                failures.Add($"run {run}: {problem} " +
                    $"(calls: {Describe(calls)}; " +
                    $"list: {string.Join(", ", kitchen.ShoppingList)})");
            }
        }

        return new(scenario.Name, passed, runs,
            inputTokens, outputTokens, failures);
    }

    static string Describe(List<FunctionCallContent> calls) =>
        string.Join(", ", calls.Select(c =>
            $"{c.Name}({string.Join(", ", c.Arguments?
                .Select(a => $"{a.Key}: {a.Value}") ?? [])})"));
}
```

A new `Kitchen` per run means every run starts from the same pantry and an empty list, so one run can't make the next one pass. No session is passed to `RunAsync`, so every run also starts without history.

Agent Framework 1.24 also ships evaluation types in `Microsoft.Agents.AI` that run each question several times and count the passes: a `LocalEvaluator` with checks in code, passed to `agent.EvaluateAsync` with `numRepetitions`. `EvaluateAsync` runs the same agent every time, so all runs would share one `Kitchen` and its list, which is why this runner builds a new one per run. [Agent Framework LLM-as-a-judge evals in C# with Claude](https://kootstra.io/writing/agent-framework-llm-as-a-judge-evals-csharp/) uses `EvaluateAsync` with checks in code and with Claude as a judge, for answers no check in code can score.

A run that doesn't finish with `ChatFinishReason.Stop` fails before its check runs. A run cut off at the output token limit may have made half its tool calls, and its list would be checked as if the agent had finished.

`response.Messages` holds every message the run produced, so `calls` contains each tool call the model asked for, across all model calls in the run. `response.Usage` covers the whole run as well. A runner test with two scripted model calls per run, reporting 100 and 200 input tokens, gets 600 input tokens for two runs: the usage of every model call in a run ends up added together in the response's `Usage`.

The runner gets its own layer 2 tests: that each run starts with an empty list, that a run cut off at the limit fails without running the check, and that the tokens add up over calls and runs. If the runner miscounts, every pass rate it reports is wrong.

`Program.cs` creates the chat client for Claude Haiku 5.5, runs every scenario ten times and prints one row per scenario, with the failures under it:

```
using System.Globalization;
using Anthropic;
using Anthropic.Core;
using Microsoft.Extensions.AI;

var apiKey = Environment.GetEnvironmentVariable("ANTHROPIC_API_KEY")
    ?? throw new InvalidOperationException("Set ANTHROPIC_API_KEY.");

IChatClient chatClient =
    new AnthropicClient(new ClientOptions { ApiKey = apiKey })
        .AsIChatClient("claude-haiku-5-5", 4096);

const int Runs = 10;
// Claude Haiku 5.5, US dollars per million tokens.
const decimal InputPrice = 0.10m;
const decimal OutputPrice = 0.50m;

decimal total = 0;
foreach (Scenario scenario in Scenarios.All)
{
    ScenarioResult result =
        await ScenarioRunner.RunAsync(chatClient, scenario, Runs);

    decimal cost = (result.InputTokens * InputPrice
        + result.OutputTokens * OutputPrice) / 1_000_000m;
    total += cost;

    Console.WriteLine(string.Create(CultureInfo.InvariantCulture,
        $"{result.Name,-22} {result.Passed,2}/{result.Runs}  "
        + $"{result.InputTokens,7} in {result.OutputTokens,6} out  "
        + $"${cost / result.Runs:0.00000} per run"));

    foreach (string failure in result.Failures)
    {
        Console.WriteLine($"  {failure}");
    }
}

Console.WriteLine(string.Create(CultureInfo.InvariantCulture,
    $"total ${total:0.0000}"));
```

The prices are Anthropic's list prices for Claude Haiku 5.5, $0.10 per million input tokens and $0.50 per million output tokens, for prompts up to 100,000 tokens. They are constants in the code, so they have to be updated when the prices change. One price for all input tokens is right here because nothing in this sample turns prompt caching on: no message or tool sets cache control, and neither Agent Framework nor the Anthropic connector adds it. So there are no cache reads or writes, the input tokens that [the tracing post](https://kootstra.io/writing/agent-framework-opentelemetry-tracing-csharp/) prices separately. Every request also stays far below 100,000 tokens. The output token limit is 4096, because Haiku 5.5's reasoning counts as output, and the runner fails any run that stops at the limit.

This is the real table, from one run of the app:

```
milk on the list       10/10    12810 in    679 out  $0.00016 per run
question only          10/10    12590 in    760 out  $0.00016 per run
no peanuts             10/10    13951 in   2957 out  $0.00029 per run
missing for a recipe   10/10    26722 in   3283 out  $0.00043 per run
total $0.0104
```

All forty runs finished with `Stop` and passed their check: the model put one milk item on the list and nothing else, answered the egg question from the pantry without adding anything, added nothing in place of peanut butter, and listed pasta without anything the pantry already had. The recipe scenario used about twice the input tokens per run of the milk scenario, and the peanut and recipe scenarios used four to five times its output tokens. Forty runs cost just over one US cent.

10/10 is not 100%. Ten runs are a small sample, and a small sample hides failures that happen now and then. If a scenario fails one run in four, ten runs in a row still all pass about one time in twenty: 0.75 to the power of 10 is 0.056. If it fails one run in ten, ten runs all pass about one time in three, and 9/10 or worse shows up the other two times. A difference between 10/10 and 9/10 says nothing on its own; a drop from 10/10 to 5/10 after a change to the instructions does.

That makes the table useful in two ways. As a regression check, the same scenarios run before and after a change to the instructions, a tool description or the model, and a large drop shows that the change broke something. As an estimate, it gets better with more runs, and every run costs money: 100 runs per scenario would cost about ten cents here, and much more with a larger model or a longer conversation. These runs don't belong in `dotnet test`. They call a paid API, and a scenario that passes nine runs in ten makes the build fail one time in ten for no change at all. The sample runs them as the app, on demand.

How high a pass rate has to be depends on what a failure costs. An assistant that sometimes looks in the pantry before adding milk and sometimes doesn't is fine at 9/10. One that adds peanuts for a household with an allergy is not acceptable at 99/100, and no number of runs shows that it will never happen. That is why the peanut rule is in `AddToShoppingList`, where a layer 1 test proves on every run that nothing with "peanut" in its name gets on the list. The rest is left to the model: whether it adds something else instead, or a product with peanuts under another name, such as satay sauce, and that is what the scenario checks. Ten passes out of ten still leave room for a failure rate of up to about one in four (one-sided, 95% confidence), so anything that must fail less often than that has to be decided in code.

`KitchenAgent.cs`, run the scenarios again and compare the "question only" row with the table above.`Pasta` in `Scenarios.cs` to `["pasta"]`, run the check tests, and then the scenarios. Any new failure in "missing for a recipe" is a failure of the check, not of the model.
