Testing an AI application is already different from testing a traditional application. A method that receives the same input does not always produce exactly the same response because language models can generate different answers.
The challenge becomes more noticeable when web search is involved.
Imagine building an application that answers questions about the latest .NET releases. Today, a search might return three official documentation pages. Tomorrow, the search index may return different pages, a new announcement may appear, or an existing page may have changed.
Even when the user submits exactly the same question, the generated answer can be different.
This creates a problem for developers who rely on traditional automated tests. A test that compares the complete AI response with a previously saved string may pass today and fail tomorrow without any application code changing.
The solution is not to stop testing AI applications. It is to change what we test.
In this article, we will explore how to test a search-enabled AI application using Amazon Bedrock Web Search, C#, and ASP.NET Core. We will focus on repeatable tests, controlled test data, citation validation, and production monitoring.
Why Web Search Makes AI Testing More Difficult
A traditional API usually produces predictable output when its input and dependencies remain unchanged.
For example, a calculation endpoint that receives two numbers should return the same result every time.
A search-enabled AI application has more variables:
- Search results can change over time.
- Web pages can be updated or removed.
- Search ranking can change.
- The model may formulate different search queries.
- The model may interpret retrieved information differently.
- Generated answers can vary even when the underlying information is similar.
Amazon Bedrock Web Search adds another important detail: the model decides whether it needs current information and can perform one or more searches during a request.
The search results come from an Amazon-maintained web index. If the initial results are insufficient, the model can reformulate its query and search again.
This means the same user question does not guarantee the same search observations or final response.
A useful testing strategy must separate application behavior from external search behavior.
Identify What Should Be Tested
Before writing tests, divide the application into separate responsibilities.
For a typical AI application, the architecture might look like this:
User
|
v
ASP.NET Core API
|
v
AI Application Service
|
v
Amazon Bedrock Responses API
|
v
Web Search Tool
|
v
Generated Answer and Citations
|
v
Response Processing
|
v
UserEach component has different testing requirements.
| Component | What to test |
|---|---|
| API endpoint | Request validation and response structure |
| AI application service | Request construction and error handling |
| Bedrock integration | Authentication, model configuration, and response parsing |
| Web Search behavior | Whether relevant information and citations are returned |
| Response processing | Citation extraction and validation |
| Frontend | Answer presentation and source links |
The most important design decision is to avoid making every application test depend on a live web search.
If the search provider returns different information, your controller validation test should not fail. The controller should be tested independently from the changing search results.
Create an Abstraction Around the AI Service
A good starting point is to define an interface for the AI functionality.
This allows the application to use Amazon Bedrock in production and a controlled implementation during automated tests.
Create an interface:
public interface IAIAnswerService
{
Task<AIAnswerResponse> AskAsync(
string question,
CancellationToken cancellationToken);
}Define the response models:
public class AIAnswerResponse
{
public string Answer { get; set; } = string.Empty;
public List<SourceReference> Sources { get; set; } = new();
}
public class SourceReference
{
public string Title { get; set; } = string.Empty;
public string Url { get; set; } = string.Empty;
}The production implementation communicates with Amazon Bedrock. The test implementation returns predefined responses.
Register the production implementation in Program.cs:
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddHttpClient<BedrockSearchService>();
builder.Services.AddScoped<IAIAnswerService, BedrockSearchService>();
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();The BedrockSearchService should implement IAIAnswerService.
This separation makes it possible to test the API without sending real requests to Amazon Bedrock.
Use a Fake Response for Repeatable Tests
A fake service returns controlled data instead of calling the actual model.
For example:
public class FakeAIAnswerService : IAIAnswerService
{
public Task<AIAnswerResponse> AskAsync(
string question,
CancellationToken cancellationToken)
{
var response = new AIAnswerResponse
{
Answer = "The latest documentation describes " +
"several platform improvements.",
Sources =
{
new SourceReference
{
Title = "Official Documentation",
Url = "https://example.com/documentation"
}
}
};
return Task.FromResult(response);
}
}The source URL is illustrative test data, not a real search result.
Now an API test can use this fake service and verify the application's behavior.
For example, with xUnit:
using Xunit;
public class AIControllerTests
{
[Fact]
public async Task AskAsync_ReturnsAnswerAndSources()
{
var service = new FakeAIAnswerService();
var result = await service.AskAsync(
"What changed in .NET?",
CancellationToken.None);
Assert.NotNull(result);
Assert.NotEmpty(result.Answer);
Assert.NotEmpty(result.Sources);
Assert.Equal(
"Official Documentation",
result.Sources[0].Title);
}
}This test is repeatable because it does not depend on search ranking, page availability, or model-generated wording.
The objective is to verify that the application correctly handles an AI response, not to test the live search engine every time the test suite runs.
Test the Bedrock Response Parser Separately
Another important area is response parsing.
Amazon Bedrock returns generated text and citation annotations through the Responses API. The application must extract these values and convert them into its own response model.
A parser should be tested using saved response fixtures.
For example, create a test JSON file:
{
"output": [
{
"type": "message",
"content": [
{
"type": "output_text",
"text": "The platform includes new improvements.",
"annotations": [
{
"type": "url_citation",
"title": "Release Documentation",
"url": "https://example.com/release",
"start_index": 0,
"end_index": 45
}
]
}
]
}
]
}The values are sample test data.
Write tests that verify:
- Generated text is extracted correctly.
- Citation titles are preserved.
- Citation URLs are preserved.
- Multiple citations are handled correctly.
- Missing annotations do not cause exceptions.
- Unexpected output items are handled safely.
- Invalid JSON produces a controlled error.
This is especially useful when an application upgrades its model configuration or changes its response-processing logic.
A saved response fixture also makes regression testing possible without depending on the current contents of the web.
However, a fixture only verifies that your parser handles that particular response structure. It does not prove that every possible Bedrock response has the same structure. Maintain fixtures for the response patterns your application supports.
Avoid Comparing the Entire Generated Answer
One of the most common mistakes in AI testing is comparing the complete response against an expected string.
For example:
Assert.Equal(
"The latest .NET release introduces performance improvements.",
response.Answer);This test is too strict for a generative application.
The model might produce:
"The latest release includes improvements that can help application performance."
The meaning is similar, but the wording is different. The test fails even though the application may be working correctly.
Instead, test specific requirements.
For example:
Assert.False(
string.IsNullOrWhiteSpace(response.Answer));
Assert.NotNull(response.Sources);
Assert.All(
response.Sources,
source =>
{
Assert.False(string.IsNullOrWhiteSpace(source.Title));
Assert.False(string.IsNullOrWhiteSpace(source.Url));
});For applications with specific business requirements, add semantic evaluation.
For example, a technical support assistant might need to mention a particular framework version or identify when the available information is insufficient.
These requirements can be evaluated using a combination of deterministic rules, structured output validation, and human review.
Validate Citations Instead of Assuming They Are Correct
A search-enabled AI application should preserve the citations returned by the model.
However, checking that a citation exists is not enough.
Consider an answer that contains a statement about a new API. The response includes a source URL, but that page may not support the particular statement.
Citation testing should therefore cover several aspects:
| Validation | Purpose |
|---|---|
| Citation exists | Confirm that source information was returned |
| URL format | Reject malformed or unsupported URLs |
| Source title | Ensure the title is not empty |
| Citation positions | Check that referenced text positions are valid |
| Source association | Evaluate whether the source supports the related claim |
| Frontend rendering | Ensure users can open and identify the source |
Some of these checks can be automated.
For example, validate that URLs use HTTP or HTTPS:
public static bool IsValidSourceUrl(string url)
{
return Uri.TryCreate(
url,
UriKind.Absolute,
out var uri)
&& (uri.Scheme == Uri.UriSchemeHttps ||
uri.Scheme == Uri.UriSchemeHttp);
}Claim-to-source relevance requires more than URL validation. It can be evaluated through curated test cases, human review, or a separate evaluation process.
Do not assume that a citation automatically proves every statement in the generated answer.
Create a Repeatable Test Dataset
For a search-enabled AI application, maintain a collection of representative questions and expected evaluation criteria.
For example:
| Test question | Expected behavior |
|---|---|
| What is the latest .NET release? | Uses current information and provides relevant citations |
| What is dependency injection? | Provides a clear explanation without requiring unnecessary search |
| What changed in a recently released API? | Identifies relevant changes and supporting sources |
| Find documentation for an unsupported feature | Avoids inventing documentation or source URLs |
| Summarize information from multiple sources | Produces a coherent summary with appropriate citations |
The expected result should describe what the application must achieve rather than prescribe an exact generated sentence.
For more reliable evaluations, maintain a set of reference facts for each question. These facts can be used to check whether the answer contains important information and avoids unsupported claims.
When the source content changes, review the expected facts instead of automatically treating the new answer as incorrect.
This is particularly important for questions about release information, security advisories, and product announcements.
Separate Automated Tests From Live Search Tests
Not every test should call Amazon Bedrock.
A practical testing strategy uses different test layers.
| Test type | Uses live Bedrock search? | Main purpose |
|---|---|---|
| Unit tests | No | Validate application logic |
| Parser tests | No | Validate response extraction |
| API integration tests | No, uses a fake service | Validate endpoints and dependency injection |
| Contract tests | Usually no | Validate expected request and response structures |
| Live smoke tests | Yes | Confirm the integration works with the actual service |
| Quality evaluations | Yes, or use controlled fixtures | Evaluate answer relevance and grounding |
For ASP.NET Core integration tests, Microsoft provides WebApplicationFactory and TestServer through the Microsoft.AspNetCore.Mvc.Testing package.
These tools allow developers to run the application in an in-memory test environment and replace dependencies with test implementations.
Live smoke tests should run separately because they depend on network access, AWS permissions, model availability, and potentially changing search results.
This keeps the main test suite fast and predictable.
Monitor Changes After Deployment
Automated tests cannot predict every change in search behavior.
A search-enabled application should also collect operational information after deployment.
Useful metrics include:
- Number of requests using Web Search.
- Bedrock request success and failure rates.
- Response latency.
- Number of returned citations.
- Requests with no useful source information.
- Token usage and associated costs.
- User feedback about answer quality.
Amazon Bedrock Web Search integrates with AWS CloudTrail. Web Search data events can help administrators audit who invoked the service, when, and from where.
CloudTrail data events are not enabled by default. Configure the appropriate trail or event data store when this monitoring is required.
Avoid logging sensitive prompts, API keys, or unnecessary user information.
It is also important to understand that CloudTrail is an auditing mechanism, not an answer-quality evaluation system. Use application-level metrics and evaluation datasets to monitor response quality.
Summary
Testing an AI application with web search requires a different approach from testing a traditional API. Search results change, web pages are updated, and model-generated answers are not guaranteed to use identical wording on every request.
The most reliable strategy is to separate application logic from live search behavior. Use fake services for repeatable API tests, saved response fixtures for parser tests, and structured evaluation criteria for generated answers.
Run live Bedrock tests separately to verify the actual integration, and monitor search activity and answer quality after deployment.
The objective is not to force an AI application to return exactly the same sentence every time. It is to ensure that the application remains reliable, handles changing information correctly, preserves citations, and produces useful answers under realistic conditions.

Join the conversation! Your thoughts help the community grow.