ASP.NET Core › API Versioning

How do you unit test that a specific API version's controller action behaves correctly, given the version-based routing?

Intermediate

Answer

Since versioned routing resolution happens at the ASP.NET Core routing/framework level (not inside your action method's logic), unit tests typically just instantiate and call the specific versioned controller class directly (e.g., ProductsV2Controller) without needing to simulate the actual HTTP routing/version-matching machinery -- reserving full routing verification (confirming a request with a given version header/URL actually reaches the intended controller) for integration tests using WebApplicationFactory.
[Fact]
public void GetAll_V2_ReturnsExpandedProductFields() {
    var controller = new ProductsV2Controller(_mockService.Object);
    var result = controller.GetAll() as OkObjectResult;
    var products = result.Value as List<ProductV2Dto>;
    Assert.Contains(products, p => p.Currency != null);  // v2-specific field
}
Real-world example A unit test suite directly tests ProductsV2Controller's business logic in isolation, while a separate integration test suite confirms that a request with 'api-version: 2.0' actually routes to that controller correctly -- keeping the two concerns cleanly separated.

Common follow-ups: What would an integration test verifying correct version routing look like?;How do you test the deprecation header behavior specifically?