AI-powered applications introduce a testing challenge that traditional application code does not have. The output of an AI model is not always predictable. The same prompt can produce different answers depending on the model, its configuration, and the context provided.
If every unit test calls a real AI model, the test suite becomes slower, more expensive, and harder to maintain. A model server may be unavailable, a cloud API may enforce rate limits, or a response may change and cause an otherwise valid test to fail.
A better approach is to separate application logic from the actual model and use fake responses during unit testing.
In .NET, Microsoft.Extensions.AI provides the IChatClient abstraction, which makes this approach straightforward. An application service can depend on IChatClient, while a test supplies a fake or mocked implementation that returns a predictable response.
This article explains how to test AI-powered services without connecting to a real model. We will create a small ASP.NET Core application service, write unit tests using xUnit and Moq, and test successful responses, input handling, exceptions, and cancellation.
Why Testing AI Features Is Different
Consider an application that uses an AI model to answer customer questions. The application receives a question, sends it to the model, and returns the generated answer.
A basic implementation might look like this:
using Microsoft.Extensions.AI;
public sealed class AssistantService
{
private readonly IChatClient _chatClient;
public AssistantService(IChatClient chatClient)
{
_chatClient = chatClient;
}
public async Task<string> AskAsync(
string question,
CancellationToken cancellationToken)
{
var response = await _chatClient.GetResponseAsync(
question,
cancellationToken: cancellationToken);
return response.Text ?? string.Empty;
}
}The service is small, but it still depends on an external AI system.
Testing this service by calling a real model introduces several problems:
- The response may change between test executions.
- Tests depend on network connectivity or a running local model server.
- Cloud model requests may increase testing costs.
- Provider rate limits can interrupt automated builds.
- Model response time can make the test suite slow.
- External service failures can make unrelated application tests fail.
For example, a test that expects the model to return the exact text "Dependency injection manages object creation" may fail when the model returns "Dependency injection helps manage object creation and dependencies."
Both responses may be correct, but an exact string comparison makes the test unreliable.
The goal of a unit test should be to verify the application's behavior, not to evaluate whether a model produces a particular answer.
Understanding IChatClient for Testing
Microsoft.Extensions.AI provides IChatClient as a common abstraction for chat-based AI services.
Instead of depending directly on an Ollama or OpenAI client, an application service can depend on IChatClient.
This separation makes it possible to replace the real model client during testing.
The architecture looks like this:
Application Service
|
v
IChatClient
|
+----------------------+
| |
v v
Real AI Client Fake AI Client
| |
v v
AI Model API Test ResponseIn production, dependency injection provides the real AI client. During testing, the test provides a mocked client that returns a predefined response.
The application service does not need to know which implementation it receives.
The GetResponseAsync method accepts chat messages, optional chat settings, and a cancellation token. It returns a ChatResponse object containing the generated response.
This common interface is what makes isolated testing possible.
Creating the Project
Create a new .NET project:
dotnet new web -n AIFeatureTesting
cd AIFeatureTestingInstall the required packages:
dotnet add package Microsoft.Extensions.AI
dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package Moq
dotnet add package Microsoft.NET.Test.SdkFor a real application, the AI provider package is also required. However, the unit tests in this article do not need an actual model provider because they use a mocked IChatClient.
You can keep the application project and test project separate:
AIFeatureTesting/
│
├── AIFeatureTesting/
│ ├── Services/
│ │ └── AssistantService.cs
│ └── Program.cs
│
└── AIFeatureTesting.Tests/
├── AssistantServiceTests.cs
└── AIFeatureTesting.Tests.csprojThis structure keeps production code separate from test code and makes it easier to run tests independently.
Creating the AI Service
First, create AssistantService.cs in the application project.
using Microsoft.Extensions.AI;
public sealed class AssistantService
{
private readonly IChatClient _chatClient;
public AssistantService(IChatClient chatClient)
{
_chatClient = chatClient;
}
public async Task<string> AskAsync(
string question,
CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(question))
{
throw new ArgumentException(
"Question cannot be empty.",
nameof(question));
}
var response = await _chatClient.GetResponseAsync(
question,
cancellationToken: cancellationToken);
return response.Text ?? string.Empty;
}
}The service validates the question before sending it to the model. It then calls IChatClient and returns the response text.
Notice that the service does not contain provider-specific code. It does not create an Ollama client, initialize an OpenAI client, or manage API credentials.
This design makes the service easier to test because the model dependency can be replaced without changing the application logic.
Creating a Fake AI Response With Moq
Moq allows developers to create a mock implementation of an interface without writing a complete fake class.
Create a test project:
dotnet new xunit -n AIFeatureTesting.Tests
cd AIFeatureTesting.Tests
dotnet add reference ../AIFeatureTesting/AIFeatureTesting.csproj
dotnet add package Microsoft.Extensions.AI
dotnet add package MoqNow create AssistantServiceTests.cs.
The first test verifies that the service returns the response provided by the mocked AI client.
using Microsoft.Extensions.AI;
using Moq;
using Xunit;
public class AssistantServiceTests
{
[Fact]
public async Task AskAsync_ReturnsFakeModelResponse()
{
var expectedResponse =
"Dependency injection manages object creation.";
var mockClient = new Mock<IChatClient>();
mockClient
.Setup(client => client.GetResponseAsync(
It.IsAny<IEnumerable<ChatMessage>>(),
It.IsAny<ChatOptions?>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(
new ChatResponse(
new ChatMessage(
ChatRole.Assistant,
expectedResponse)));
var service = new AssistantService(mockClient.Object);
var result = await service.AskAsync(
"What is dependency injection?");
Assert.Equal(expectedResponse, result);
}
}Let's understand the important parts.
Creating the Mock Client
var mockClient = new Mock<IChatClient>();This creates a mock implementation of IChatClient.
The test does not need an AI server, API key, or internet connection.
Configuring the Fake Response
mockClient
.Setup(client => client.GetResponseAsync(
It.IsAny<IEnumerable<ChatMessage>>(),
It.IsAny<ChatOptions?>(),
It.IsAny<CancellationToken>()))
.ReturnsAsync(
new ChatResponse(
new ChatMessage(
ChatRole.Assistant,
expectedResponse)));This configuration tells Moq to return a predefined ChatResponse whenever the service calls GetResponseAsync with matching method arguments.
It does not send a request to an actual model.
The test can now verify how the application handles a known response.
Verifying the Result
Assert.Equal(expectedResponse, result);The assertion checks whether AssistantService returns the expected text.
This is a deterministic test because the response is controlled by the test rather than generated by an external model.
Testing Empty and Invalid Questions
Input validation should be tested separately from model communication.
The service already rejects empty or whitespace-only questions. We can verify this behavior without configuring a mock response.
Join the conversation! Your thoughts help the community grow.