gpt4 book ai didi

c# - 如何创建 Microsoft.AspNetCore.Http.HttpRequest 的实例进行测试?

转载 作者:行者123 更新时间:2023-12-04 13:54:36 25 4
gpt4 key购买 nike

我希望创建一个带有填充数据的 HttpRequest 实例,以便我可以测试一个方法。
我需要将 Microsoft.AspNetCore.Http.HttpRequest 作为参数传递给函数。
我如何实例化它?

[Route("/summary/{id}")]
public IActionResult Account(int id)
{
var summary = RequestHelper.ParseRequest(Request);
}
选项来自包
https://github.com/louthy/language-ext
public static Option<SummaryRequest> ParseRequest(HttpRequest request)
{
if (request== null)
{
var query = request.Query;

var result = new SummaryRequest();

var locations = ExtractData(query, "location");
var categories = ExtractData(query, "categories[]");
var titles = ExtractData(query, "titles");

}
}

public static Option<SummaryRequest> ParseRequest(HttpRequest request)
{
if (request== null)
{
var query = request.Query;

var result = new SummaryRequest();

var locations = ExtractData(query, "location");
var categories = ExtractData(query, "categories[]");
var titles = ExtractData(query, "titles");
}

return new SummaryRequest();
}

public static Either<Exception, string[]> ExtractData(IEnumerable<KeyValuePair<String, StringValues>> query, string filter)
{
try
{
return query.First(x => x.Key.ToLower() == filter).Value.ToString().Split(',').ToArray();
}
catch (Exception ex)
{
return ex;
}
}
单元测试示例
 [TestMethod]
[TestCategory(Test.RequestParser)]
public void ParseRequest_WithHttpRequest_ReturnResultOnSuccess()
{
// var request = this doesn't compile I need an instance of
// Microsoft.AspNetCore.Http.HttpRequest

var result = Helper.ParseRequest(request);
}

最佳答案

您可以使用 Request property of DefaultHttpContext .这有点令人费解,因为您必须单独指定许多属性(与例如 WebRequest.Create 相比),但以下内容对我有用:

var httpContext = new DefaultHttpContext();
httpContext.Request.Method = "POST";
httpContext.Request.Scheme = "http";
httpContext.Request.Host = new HostString("localhost");
httpContext.Request.ContentType = "application/json";
var stream = new MemoryStream();
var writer = new StreamWriter(stream);
await writer.WriteAsync("{}");
await writer.FlushAsync();
stream.Position = 0;
httpContext.Request.Body = stream;

关于c# - 如何创建 Microsoft.AspNetCore.Http.HttpRequest 的实例进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64634428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com