[英]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.我无法使用 moq 模拟 _httpContext.GetRquestedApiVersion 方法,因为它是一种扩展方法。 How can I fill httpContext with test version details, so that the original GetRequestedApiVersion method works?如何使用测试版本详细信息填充 httpContext,以便原始 GetRequestedApiVersion 方法有效?
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
. HttpContext.GetRequestedApiVersion()
扩展方法只是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.很有可能,您不需要通过所有依赖注入 (DI)、配置、请求管道或解析来模拟请求的 API 版本。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.