API versioning allows an ASP.NET Core application to support different versions of an endpoint while existing clients continue using the contracts they were built against. This is useful when an application evolves over time. A new version might introduce additional fields, change validation rules, or return a different response structure without immediately breaking older clients.
However, API versioning also creates a testing challenge. When an application supports multiple versions, developers need to verify that every version behaves correctly. Creating a separate test project for each API version may seem straightforward, but it often leads to duplicated test setup, repeated configuration, and more maintenance work.
A better approach is to use one integration test project with shared test infrastructure and version-specific test cases. ASP.NET Core provides WebApplicationFactory for hosting an application in memory, while xUnit supports parameterized tests that can execute the same test logic against different API versions.
This article explains how to organize integration tests for multiple API versions in a single .NET test project, verify different response contracts, and keep version-specific behavior covered as an application evolves.
Why Multiple API Versions Need Shared Test Coverage
Consider an application that initially exposes a product endpoint:
GET /api/v1/products
The first version returns basic product information:
{
"id": 101,
"name": "Laptop"
}
Later, the application introduces a second version:
GET /api/v2/products
The new version returns additional information:
{
"id": 101,
"name": "Laptop",
"category": "Electronics",
"isAvailable": true
}
Both versions may use the same database and business services, but their public contracts are different.
Testing only version 2 does not guarantee that version 1 still works. A developer might accidentally change a shared service or response mapping in a way that breaks older clients.
At the same time, duplicating the entire test suite for each version creates unnecessary maintenance. If authentication configuration, database setup, or test data changes, developers may need to update several test projects.
A shared integration test project avoids this duplication. It can start the application once through a reusable test factory and execute tests against different versioned endpoints.
Set Up the Application With API Versioning
For this example, use the ASP.NET API Versioning library, which provides API versioning support for ASP.NET Core controllers and Minimal APIs.
Install the MVC integration package:
dotnet add package Asp.Versioning.Mvc
Configure API versioning in Program.cs:
using Asp.Versioning;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
builder.Services
.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = false;
options.ReportApiVersions = true;
options.ApiVersionReader = new UrlSegmentApiVersionReader();
})
.AddMvc();
var app = builder.Build();
app.MapControllers();
app.Run();
public partial class Program
{
}
The configuration uses URL-segment versioning. A request identifies its API version directly in the route, such as /api/v1.0/products or /api/v2.0/products.
Setting AssumeDefaultVersionWhenUnspecified to false ensures that clients must provide a version instead of silently receiving the default version.
The ReportApiVersions option enables supported and deprecated API version information in response headers where applicable.
The partial Program declaration makes the application entry point accessible to the integration test project. This allows WebApplicationFactory to start the actual application configuration instead of requiring a separate test-only startup implementation.
Create Two API Versions
The application can expose separate controllers for different versions while sharing the same route structure.
The first controller implements version 1:
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion("1.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV1Controller : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new[]
{
new
{
Id = 101,
Name = "Laptop"
},
new
{
Id = 102,
Name = "Keyboard"
}
};
return Ok(products);
}
}
Version 2 provides an expanded response:
using Asp.Versioning;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[ApiVersion("2.0")]
[Route("api/v{version:apiVersion}/products")]
public class ProductsV2Controller : ControllerBase
{
[HttpGet]
public IActionResult GetProducts()
{
var products = new[]
{
new
{
Id = 101,
Name = "Laptop",
Category = "Electronics",
IsAvailable = true
},
new
{
Id = 102,
Name = "Keyboard",
Category = "Accessories",
IsAvailable = true
}
};
return Ok(products);
}
}
Both controllers use the same route pattern, but their API version attributes determine which version they serve.
In a production application, these controllers would normally call shared application services instead of defining response data directly. The example keeps the endpoint implementation small so that the testing approach remains easy to understand.
The important point is that the API versions have separate contracts. Integration tests should verify those contracts rather than only checking whether an endpoint returns HTTP 200.
Create One Integration Test Project
Create a test project:
dotnet new xunit -n ProductApi.Tests
Add the ASP.NET Core integration testing package:
dotnet add ProductApi.Tests package Microsoft.AspNetCore.Mvc.Testing
The test project should also reference the API project:
dotnet add ProductApi.Tests reference ProductApi/ProductApi.csproj
The integration test project now has access to the application entry point and the tools needed to host the API in memory.
A typical structure looks like this:
ProductApi/
├── Controllers/
│ ├── ProductsV1Controller.cs
│ └── ProductsV2Controller.cs
├── Program.cs
└── ProductApi.csproj
ProductApi.Tests/
├── Api/
│ └── ProductVersionTests.cs
├── Infrastructure/
│ └── ProductApiFactory.cs
└── ProductApi.Tests.csproj
This structure separates application code, test infrastructure, and version-specific test cases without requiring a different test project for every API version.
Reuse WebApplicationFactory Across API Versions
WebApplicationFactory starts the ASP.NET Core application using an in-memory test server. Tests can send HTTP requests through an HttpClient without deploying the application to a real web server.
Create a reusable factory:
using Microsoft.AspNetCore.Mvc.Testing;
namespace ProductApi.Tests.Infrastructure;
public class ProductApiFactory
: WebApplicationFactory<Program>
{
}
This factory uses the application's normal startup configuration. You can extend it later to replace external services, configure a test database, or provide test-specific application settings.
For example, if the API uses Entity Framework Core with SQL Server, the test factory can replace the production database registration with a test database. This allows integration tests to exercise the real application pipeline without depending on a production database.
The factory should be shared through an xUnit fixture so that related tests can reuse the same application host.
Test Multiple API Versions With xUnit
Now create a test class that uses the shared factory:
using System.Net;
using System.Text.Json;
using ProductApi.Tests.Infrastructure;
namespace ProductApi.Tests.Api;
public class ProductVersionTests
: IClassFixture<ProductApiFactory>
{
private readonly HttpClient _client;
public ProductVersionTests(ProductApiFactory factory)
{
_client = factory.CreateClient();
}
[Theory]
[InlineData("v1.0", false)]
[InlineData("v2.0", true)]
public async Task GetProducts_ReturnsExpectedContract(
string version,
bool includesAvailability)
{
var response = await _client.GetAsync(
$"/api/{version}/products");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var content = await response.Content.ReadAsStringAsync();
using var document = JsonDocument.Parse(content);
var product = document.RootElement[0];
Assert.True(product.TryGetProperty("id", out _));
Assert.True(product.TryGetProperty("name", out _));
Assert.Equal(
includesAvailability,
product.TryGetProperty("isAvailable", out _));
}
}
The [Theory] attribute tells xUnit to execute the same test method with multiple input values. Each [InlineData] entry represents a different API version and its expected response behavior.
The test verifies that both versions return HTTP 200 and contain the common product fields. It then checks whether the isAvailable field exists according to the expected contract.
This avoids writing two nearly identical test methods just to change the requested URL.
However, this example checks only a small part of each response. For more complex APIs, separate assertions should verify required fields, data types, validation behavior, and response values.
Test Version-Specific Response Contracts
As APIs evolve, checking that a field exists may not be enough. A response could contain the correct property names but still return incorrect values or types.
A stronger test can verify the actual contract of each version.
For example:
[Fact]
public async Task GetProducts_V1_ReturnsBasicProductFields()
{
var response = await _client.GetAsync("/api/v1.0/products");
response.EnsureSuccessStatusCode();
var products = await response.Content
.ReadFromJsonAsync<List<ProductV1Response>>();
Assert.NotNull(products);
Assert.NotEmpty(products);
Assert.Equal(101, products[0].Id);
Assert.Equal("Laptop", products[0].Name);
}
Define a response model for version 1:
public record ProductV1Response(
int Id,
string Name);
For version 2, use a separate response model:
public record ProductV2Response(
int Id,
string Name,
string Category,
bool IsAvailable);
The version 2 test can then deserialize the response into its expected model:
[Fact]
public async Task GetProducts_V2_ReturnsExtendedProductFields()
{
var response = await _client.GetAsync("/api/v2.0/products");
response.EnsureSuccessStatusCode();
var products = await response.Content
.ReadFromJsonAsync<List<ProductV2Response>>();
Assert.NotNull(products);
Assert.NotEmpty(products);
Assert.Equal("Electronics", products[0].Category);
Assert.True(products[0].IsAvailable);
}
Separate response models make the contract differences explicit. This is especially useful when versions have different required fields, data types, or nested response structures.
For a large application, these response models can be organized into version-specific test folders while keeping the same test project and shared infrastructure.
Test Unsupported and Deprecated API Versions
A complete versioning test suite should also check what happens when clients request unsupported versions.
For example, a request to:
GET /api/v3.0/products
should not silently return version 1 or version 2 data.
The expected status code depends on the API versioning configuration and version-reading approach. For URL-segment versioning, an unsupported version may result in a route that does not match, while other version readers can produce different error responses.
Write the test according to the behavior your application intentionally exposes:
[Fact]
public async Task GetProducts_UnsupportedVersion_DoesNotReturnSuccess()
{
var response = await _client.GetAsync("/api/v3.0/products");
Assert.False(response.IsSuccessStatusCode);
}
If the application has a defined error contract for unsupported versions, assert the exact status code and error response instead of accepting any unsuccessful response.
For APIs that support deprecation, also test the version discovery headers. When version reporting is enabled, the application can advertise supported and deprecated versions through api-supported-versions and api-deprecated-versions response headers.
This helps catch mistakes in version retirement policies before they reach production.
Keep Test Infrastructure Shared but Test Behavior Separate
A single test project does not mean every test must be placed in one class. The goal is to share expensive infrastructure while keeping version-specific behavior easy to understand.
For example:
ProductApi.Tests/
├── Infrastructure/
│ └── ProductApiFactory.cs
├── Contracts/
│ ├── ProductV1ContractTests.cs
│ └── ProductV2ContractTests.cs
├── Compatibility/
│ └── ProductCompatibilityTests.cs
└── Validation/
└── ProductValidationTests.cs
The factory can be reused by all test classes, while each class focuses on a particular contract or behavior.
This organization becomes valuable when an API has several versions. Version 1 might require legacy validation rules, while version 2 supports additional filters or a different response structure. Keeping these behaviors separate makes the test suite easier to maintain without duplicating application startup and configuration.
Also avoid sharing mutable test data between tests unless the fixture is designed for that purpose. A shared application host does not automatically make database state safe to share. Use isolated test data, transactions, or database cleanup strategies so that tests do not depend on execution order.
Conclusion
Testing multiple API versions does not require a separate test project for every version. ASP.NET Core's WebApplicationFactory provides a reusable integration testing environment, and xUnit theories allow the same test logic to run against multiple versioned endpoints.
The most effective approach is to share the application factory and test infrastructure while keeping version-specific contracts and behavior clearly separated. Verify not only that each endpoint responds successfully, but also that its response structure, validation rules, and compatibility expectations remain correct.
As an API evolves, these tests help protect existing clients while developers introduce new versions. A well-organized integration test project makes that protection easier to maintain without multiplying projects and duplicated setup.
Join the conversation! Your thoughts help the community grow.