Testing an AI agent API is different from testing a traditional ASP.NET Core API.
A normal API usually receives a known request, executes predictable application logic, and returns a response that can be compared with an expected result. An AI agent may call a language model, choose different tools, generate different wording, retry an operation, or take a different path based on the model's response.
That does not mean AI agent APIs cannot be tested reliably. It means the test strategy needs to separate deterministic application behavior from non-deterministic model behavior.
One practical approach is to replace the real AI model with deterministic mocks during automated tests and record representative conversations that can be replayed later. This allows developers to test the workflow, tool execution, validation, authorization, error handling, and persistence without depending on a live model.
This article explains how to build that testing approach in an ASP.NET Core application.
Why Traditional API Tests Are Not Enough for AI Agents
Consider an API endpoint:
POST /api/agent/chatThe user sends:
{
"message": "Check my order and tell me whether it has shipped."
}The application may perform this workflow:
User Request
|
v
ASP.NET Core API
|
v
AI Model
|
v
Tool Selection
|
v
Order API
|
v
AI Model
|
v
Final ResponseThere are several points where the result can vary.
The model may choose a different tool.
The model may produce different wording.
The model may decide that additional information is required.
A tool may fail.
A retry may happen.
The model provider may change its response format.
If the automated test expects the exact final text, the test can become unreliable.
For example, this test is fragile:
Assert.Equal(
"Your order has been shipped and is currently in transit.",
response.Message);A perfectly valid model response could instead be:
Your order has shipped and is currently in transit.The business result is the same, but the string is different.
The better approach is to test the behavior that matters.
Separate Model Behavior From Application Behavior
A useful testing architecture separates the AI model behind an interface.
public interface IAgentModel
{
Task<AgentModelResponse> CompleteAsync(
AgentModelRequest request,
CancellationToken cancellationToken);
}The production application can use a real model implementation.
IAgentModel
|
+-- ProductionAgentModel
|
+-- DeterministicMockAgentModel
|
+-- ReplayAgentModelThe application workflow does not need to know which implementation is being used.
This is the foundation for reliable testing.
Create a Deterministic Model Response
A test model should return a predefined response.
For example:
public sealed class DeterministicAgentModel : IAgentModel
{
private readonly AgentModelResponse _response;
public DeterministicAgentModel(AgentModelResponse response)
{
_response = response;
}
public Task<AgentModelResponse> CompleteAsync(
AgentModelRequest request,
CancellationToken cancellationToken)
{
return Task.FromResult(_response);
}
}The test controls the model response completely.
Suppose the application expects the model to request an order lookup:
var modelResponse = new AgentModelResponse
{
ToolCall = new AgentToolCall
{
Name = "get_order",
Arguments = new Dictionary<string, object>
{
["orderId"] = "48291"
}
}
};The test can now verify what the application does when the model makes that specific tool request.
Test the Agent Workflow Instead of the Model
The goal of the application test should not be to determine whether the language model is intelligent.
The goal should be to determine whether the application correctly handles the model's output.
For example:
Model requests get_order
|
v
Application validates tool call
|
v
Application calls OrderService
|
v
Application sends result back to model
|
v
Application returns responseThe model is simply a controlled dependency in this test.
This makes failures much easier to understand.
If the test fails because the order service was not called, the problem belongs to application code.
Use ASP.NET Core Integration Tests
For an agent API, integration tests are often more useful than testing every class independently.
ASP.NET Core's WebApplicationFactory can start the application using a test configuration.
A simplified test setup can look like this:
public class AgentApiTests
: IClassFixture<WebApplicationFactory<Program>>
{
private readonly WebApplicationFactory<Program> _factory;
public AgentApiTests(WebApplicationFactory<Program> factory)
{
_factory = factory;
}
[Fact]
public async Task Agent_Should_Return_Order_Status()
{
var client = _factory.CreateClient();
var response = await client.PostAsJsonAsync(
"/api/agent/chat",
new
{
message = "Check order 48291"
});
response.EnsureSuccessStatusCode();
var result =
await response.Content.ReadFromJsonAsync<AgentResponse>();
Assert.NotNull(result);
}
}The important part is replacing the real AI dependency before the request reaches the application.
Replace the AI Service During Testing
If the application registers the model through dependency injection:
builder.Services.AddScoped<IAgentModel, ProductionAgentModel>();the test application can replace it.
Conceptually:
builder.Services.AddScoped<IAgentModel, DeterministicAgentModel>();A more flexible test factory can accept the model implementation as a dependency.
public class AgentTestFactory
: WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(
IWebHostBuilder builder)
{
builder.ConfigureServices(services =>
{
services.RemoveAll<IAgentModel>();
services.AddScoped<IAgentModel>(
_ => CreateTestModel());
});
}
private IAgentModel CreateTestModel()
{
return new DeterministicAgentModel(
new AgentModelResponse
{
Message = "Order is currently in transit."
});
}
}Now the API test runs against the actual ASP.NET Core application pipeline while controlling the AI dependency.
That is a useful balance between unit testing and full end-to-end testing.
Test Tool Calls Separately
Agent applications often depend heavily on tools.
For example:
get_order
check_payment
check_shipping
create_ticket
send_emailEach tool should have a clear contract.
public interface IOrderTool
{
Task<OrderResult> GetOrderAsync(
string orderId,
CancellationToken cancellationToken);
}The test can replace the real implementation with a controlled fake.
public sealed class FakeOrderTool : IOrderTool
{
public Task<OrderResult> GetOrderAsync(
string orderId,
CancellationToken cancellationToken)
{
return Task.FromResult(
new OrderResult
{
OrderId = orderId,
Status = "Shipped"
});
}
}Now the test can verify whether the agent correctly handles the tool result.
This is much more reliable than calling the real order service from every automated test.
Validate Tool Arguments
One of the most important agent testing scenarios is invalid tool input.
Suppose the model produces:
{
"tool": "get_order",
"arguments": {
"orderId": ""
}
}The application should not blindly execute the tool.
Test this behavior directly.
[Fact]
public async Task Empty_Order_Id_Should_Not_Call_Order_Tool()
{
var result = await agent.ExecuteAsync(
new AgentRequest
{
Message = "Check my order"
},
CancellationToken.None);
Assert.Equal(
AgentExecutionStatus.InvalidToolRequest,
result.Status);
}This type of validation is especially important because the model is an untrusted input source from an application security perspective.
The application should validate tool names, argument types, required fields, authorization, and allowed operations before executing anything.
Replayable Conversations
A single test case is not enough for complex agents.
A better approach is to store representative conversations as test fixtures.
For example:
{
"name": "order-shipping-status",
"messages": [
{
"role": "user",
"content": "Check order 48291"
},
{
"role": "assistant",
"tool": "get_order",
"arguments": {
"orderId": "48291"
}
},
{
"role": "tool",
"name": "get_order",
"content": {
"status": "Shipped"
}
},
{
"role": "assistant",
"content": "Your order has shipped."
}
]
}The exact fixture format is less important than keeping the conversation reproducible.
The replay test loads the conversation and feeds the same sequence into the application.
Recorded Conversation
|
v
Replay Test
|
v
Agent Workflow
|
v
Expected Tool Calls
Expected State
Expected ResultThis allows developers to reproduce a production bug without repeatedly calling the live model.
Replay the Important Parts, Not Just the Final Message
A replay system becomes much more useful when it captures tool interactions.
Instead of recording only:
User -> Assistantrecord:
User
|
v
Model
|
v
Tool Call
|
v
Tool Result
|
v
Model
|
v
Final ResponseNow a test can verify that the agent followed the correct execution path.
For example:
Assert.Collection(
execution.ToolCalls,
call =>
{
Assert.Equal("get_order", call.Name);
Assert.Equal("48291", call.Arguments["orderId"]);
});This gives much stronger coverage than comparing final text.
Test Model Failures
The AI model itself can fail.
A test suite should simulate these situations.
Examples include:
Model timeout
Invalid model response
Malformed tool call
Unknown tool name
Missing required argument
Unexpected response format
Rate limit response
Temporary provider failureA deterministic mock makes these cases easy to test.
public sealed class FailingAgentModel : IAgentModel
{
public Task<AgentModelResponse> CompleteAsync(
AgentModelRequest request,
CancellationToken cancellationToken)
{
throw new TimeoutException(
"Simulated model timeout.");
}
}The test can then verify that the API returns an appropriate result rather than exposing an internal exception.
Test Retry Behavior
Retries should also be deterministic.
For example, create a mock that fails twice and succeeds on the third call.
public sealed class RetryableAgentModel : IAgentModel
{
private int _attempts;
public Task<AgentModelResponse> CompleteAsync(
AgentModelRequest request,
CancellationToken cancellationToken)
{
_attempts++;
if (_attempts < 3)
{
throw new TimeoutException(
"Temporary model failure.");
}
return Task.FromResult(
new AgentModelResponse
{
Message = "Request completed."
});
}
}The test can verify:
Assert.Equal(3, model.AttemptCount);and also verify that the final response is successful.
This is much safer than waiting for an actual model provider to fail during testing.
Test Duplicate Tool Execution
Duplicate tool execution is a major concern for agents that perform side effects.
Suppose the agent creates a support ticket.
The model requests:
create_ticketThe tool succeeds, but the application crashes before storing the result.
After retry, the agent may execute:
create_ticketagain.
The test suite should explicitly cover this scenario.
First attempt
|
+--> Ticket created
|
+--> State not persisted
Retry
|
+--> Same operation
|
+--> Existing ticket returnedThe test should verify that the application uses the appropriate idempotency mechanism.
This is one of the places where integration tests provide more value than simple controller tests.
Test Authorization Around Tools
An AI model should not be allowed to decide whether an operation is authorized.
For example, the model might request:
delete_customerThe application must independently verify whether the current user can perform that action.
A test should prove that unauthorized tool calls are rejected.
[Fact]
public async Task Unauthorized_Tool_Call_Should_Be_Rejected()
{
var result = await agent.ExecuteAsync(
new AgentRequest
{
Message = "Delete customer 1001"
},
CancellationToken.None);
Assert.Equal(
AgentExecutionStatus.Unauthorized,
result.Status);
}This test protects an important security boundary.
Compare Semantic Results Instead of Exact AI Wording
For final responses, exact string comparisons are often inappropriate.
Instead, test the important properties.
For example:
Assert.Contains(
"shipped",
result.Message,
StringComparison.OrdinalIgnoreCase);For more complex responses, deserialize structured output whenever possible.
Instead of asking the model to produce:
Your order has been shipped and is currently in transit.use structured data internally:
{
"orderStatus": "Shipped",
"deliveryStatus": "InTransit"
}The application can then generate the user-facing message separately.
This makes automated testing significantly easier.
Keep Test Fixtures Versioned
Replay fixtures are part of the application's test assets.
Store them with the source code when they do not contain sensitive production data.
A useful structure is:
tests/
AgentTests/
Fixtures/
order-shipped.json
order-delayed.json
missing-order.json
tool-timeout.json
unauthorized-action.jsonEach fixture should represent a meaningful behavior.
Avoid creating hundreds of nearly identical fixtures. Focus on scenarios that represent different branches or failure modes.
Test Deterministic State Transitions
The workflow state itself should be tested independently from AI output.
For example:
Created
|
v
Running
|
v
WaitingForApproval
|
v
Running
|
v
CompletedInvalid transitions should also be rejected.
For example:
Completed -> Runningmay not be valid in the application's workflow model.
A test should verify this behavior.
[Fact]
public void Completed_Workflow_Cannot_Return_To_Running()
{
var workflow = new WorkflowState
{
Status = WorkflowStatus.Completed
};
Assert.Throws<InvalidOperationException>(
() => workflow.Start());
}This prevents AI-driven execution from accidentally bypassing application state rules.
A Practical Testing Architecture
A production-oriented AI agent test setup can look like this:
ASP.NET Core API
|
v
Agent Workflow
|
+-------------+-------------+
| |
v v
IAgentModel Tool Interfaces
| |
+-----+-----+ +------+------+
| | | |
Production Deterministic Real Tools Test Fakes
Model Mock
|
v
Replay FixturesThis structure allows different test levels.
Unit tests verify individual workflow components.
Integration tests verify the ASP.NET Core pipeline.
Replay tests verify complete agent conversations.
End-to-end tests verify the real model and real services in a controlled environment.
Not every test needs to use the real AI model.
Recommended Test Layers
Test type | AI model | External tools | Main purpose |
|---|---|---|---|
Unit test | Mock | Mock | Business logic |
Integration test | Deterministic mock | Fake | API and workflow behavior |
Replay test | Recorded response | Fake or recorded | Conversation behavior |
End-to-end test | Real model | Real or staging | Full system validation |
Production monitoring | Real model | Real | Detect unexpected behavior |
Most automated tests should remain deterministic.
Real model tests should be fewer and focused on validating integration and model-dependent behavior.
Common Mistakes
Calling the Real AI Model in Every Test
This makes tests slow, expensive, and unpredictable.
Use deterministic mocks for normal automated testing.
Testing Only the Final Text
A final response can look correct even when the agent called the wrong tool or skipped an important validation step.
Verify tool calls and state transitions.
Recording Sensitive Production Conversations
Real conversations can contain customer information, credentials, or business data.
Sanitize fixtures before storing them in source control.
Ignoring Tool Failures
The agent depends on tools, so test timeouts, invalid responses, authorization failures, and service errors.
Using Random Mock Responses
Randomness defeats deterministic testing.
The same test should produce the same result every time.
Testing Only Successful Conversations
Production failures are often more valuable test scenarios than happy paths.
Include interrupted workflows, duplicate requests, invalid tool calls, and dependency failures.
Best Practices
Put the AI model behind an interface.
Use deterministic model implementations in automated tests.
Keep replayable conversation fixtures.
Verify tool calls, not only final responses.
Validate every tool request before execution.
Test authorization independently of model decisions.
Simulate model and dependency failures.
Test retry and idempotency behavior.
Test workflow state transitions.
Keep sensitive data out of replay fixtures.
Use structured internal results where possible.
Reserve real-model tests for scenarios that actually require model behavior.
Advantages and Disadvantages
Approach | Advantages | Disadvantages |
|---|---|---|
Real model in every test | Closest to production | Slow, expensive, non-deterministic |
Deterministic mock | Fast and repeatable | Does not validate actual model behavior |
Recorded conversation replay | Reproduces complex scenarios | Fixtures require maintenance |
Full end-to-end testing | Highest system coverage | More expensive and harder to diagnose |
Structured tool testing | Strong business validation | Requires clear tool contracts |
The most practical solution is a combination rather than choosing one approach.
Deterministic tests should provide the foundation, replay tests should cover realistic workflows, and a smaller set of end-to-end tests should validate the complete system.
Troubleshooting Checklist
When an AI agent test is unstable, check:
Is the real model being called unexpectedly?
Is the model response deterministic?
Are tool results fixed for the test?
Does the test depend on exact AI-generated wording?
Are retries changing the expected execution path?
Is a shared mutable mock being reused across tests?
Does the replay fixture contain enough tool interactions?
Are asynchronous operations properly awaited?
Can the same test run successfully multiple times?
Are external services being called accidentally?
If a test passes ten times and fails once without any code change, look for hidden non-determinism before changing the assertion.
Summary
Testing AI agent APIs requires a different approach from testing traditional request-and-response APIs. The language model can produce different outputs, select different tools, and behave differently across executions.
The application code, however, should remain predictable and testable.
Putting the AI model behind an interface allows automated tests to replace it with deterministic responses. Replayable conversations provide a way to reproduce realistic agent workflows, including tool calls and intermediate results.
The strongest test strategy combines deterministic mocks, replay fixtures, tool-level validation, state-transition testing, and a smaller number of real-model end-to-end tests.
The goal is not to prove that an AI model always produces the same response. The goal is to prove that the application behaves correctly when the model produces a known class of responses, including valid requests, invalid tool calls, failures, retries, and unexpected conditions.
That separation makes AI agent APIs much easier to test, debug, and maintain as the application grows.

Join the conversation! Your thoughts help the community grow.