Home > Software engineering >  How do you set the apiversion when unit testing a versioned api controller?
How do you set the apiversion when unit testing a versioned api controller?

Time:03-11

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");

CodePudding user response:

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);
  • Related