[SOLVED] How do you set the apiversion when unit testing a versioned api controller?

Issue

I am trying to test a versioned controller and one of the routes uses HttpContext.GetRequestedApiVersion to make a decision. Whilst I can test for null in the controller, and thereby set a "default" version, I don’t know how to set the api version in my unit test so that I can test the "non-default" path. Is this possible? Below is the code where I setup the mock controller.

var analysisController = new AnalysisController(mockAnalyticsService.Object, mockBatchService.Object, mockConfig.Object);

addHttpContext(analysisController);
addUserContext(analysisController, mockUserContext.Object);
analysisController.HttpContext.Request.Headers.Add("Content-MD5", "/F4DjTilcDIIVEHn/nAQsA==");
analysisController.HttpContext.Request.Headers.Add("Content-Type", "application/octet-stream");

Solution

Turns out I didn’t need to mock anything in order to set the version.

var mockFeature = new ApiVersioningFeature(analysisController.HttpContext);
var version = new ApiVersion(2, 0);
mockFeature.RequestedApiVersion = version;

analysisController.HttpContext.Features.Set<IApiVersioningFeature>(mockFeature);

Answered By – nathanjw

Answer Checked By – Mildred Charles (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *