I wish to create an instance of HttpRequest with populated data so I can test a method.
I need to pass Microsoft.AspNetCore.Http.HttpRequest as a parameter to a function.
How do I instantiate it?
[Route("/summary/{id}")]
public IActionResult Account(int id)
{
var summary = RequestHelper.ParseRequest(Request);
}
Options is from the package 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;
}
}
Unit Test Example
[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);
}
HttpRequestis an abstract type, you can create a mock and setup all expected propertiesParseRequestmethod? The query should be somewhat simpler to stub as there is QueryCollection implementation since 3.1 that you can just populate with a dictionary. Alternatively, you can accept the wordyIEnumerable<KeyValuePair<String, StringValues>>and use dictionary directly.