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, 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.
Note
The code runs on Claude Haiku 5.5, but it depends only on
IChatClient: the first post 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 kitchen with a pantry and a shopping list
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.
Layer 1: test the code the model never decides
The tests go in a second project next to the app, with xUnit v3 and NSubstitute 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.
Layer 2: test the wiring with a scripted model
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.
Layer 3: scenarios that check what the agent did
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.
A runner without a framework
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>() .Source:https://dev.to/nkootstra/agent-framework-tests-and-pass-rates-in-c-with-claude-4d94Related posts
Watch out, AlphaFold: Claude and ChatGPT’s new biology skills wow scientists

Walmart drops Apple Pay support from its app and website
![New Gemini setting lets you keep chat history, but turn off AI training [U]](https://9to5google.com/wp-content/uploads/sites/4/2026/05/gemini-app-5.jpg?quality=82&strip=all&w=1600)