简体   繁体   中英

How to set api version related data to httpcontext for unit testing in .net core?

I have the following method in my controller

        private string GetPathBase()
        {
            return _configuration["ApiPathBase"] + $"/v{_httpContext.GetRequestedApiVersion().MajorVersion}";
        }

I am not able to mock _httpContext.GetRquestedApiVersion method using moq, as it is an extension method. How can I fill httpContext with test version details, so that the original GetRequestedApiVersion method works?

            var controllerContextMock = new Mock<ControllerContext>();

            var query = new Mock<IQueryCollection>();
            var request = new Mock<HttpRequest>();
            var httpContext = new Mock<HttpContext>();

            var response = new Mock<HttpResponse>();

            query.SetupGet(q => q["api-version"]).Returns(new StringValues("42.0"));
            request.SetupGet(r => r.Query).Returns(query.Object);                
            httpContext.SetupGet(c => c.Request).Returns(request.Object);
            httpContext.SetupGet(c => c.Response).Returns(response.Object);
            httpContext.SetupProperty(c => c.Items, new Dictionary<object, object>());
            httpContext.SetupProperty(c => c.RequestServices, Mock.Of<IServiceProvider>());

            controllerContextMock.Object.HttpContext = httpContext.Object;

The HttpContext.GetRequestedApiVersion() extension method is just a shortcut to IApiVersioningFeature.RequestedApiVersion . In all likelihood, you don't need to through all the dependency injection (DI), configuration, request pipeline, or parsing to simulate the requested API version. You can explicitly set it up in a test.

For example:

// arrange
var httpContext = new Mock<HttpContext>();
var features = new FeatureCollection();
IApiVersioningFeature feature = new ApiVersioningFeature(httpContext.Object);

feature.RequestedApiVersion = new ApiVersion(2, 0);
features.Set(feature);
httpContext.SetupGet(c => c.Features).Returns(features);

// act
var result = httpContext.Object.GetRequestedApiVersion();

// assert
result.Should().Be(feature.RequestedApiVersion);

You can setup or modify this approach any number of ways, but ultimately you solve a bunch of problems by simply setting up the feature to what it's expected to resolve to. If you really wanted to, you could even mock the feature:

var feature = new Mock<IApiVersioningFeature>();

feature.SetupProperty(f => f.RequestedApiVersion, new ApiVersion(2, 0));

var features = new FeatureCollection();
var httpContext = new Mock<HttpContext>();

features.Set(feature.Object);
httpContext.SetupGet(c => c.Features).Returns(features);

// TODO: remaining setup

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM