How to create an instance of Microsoft.AspNetCore.Http.HttpRequest for testing?

Viewed 3208

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);
 }
1 Answers

You can use the Request property of DefaultHttpContext. It's a bit convoluted since you have to specify a lot of properties separately (compared to e.g. WebRequest.Create), but the following worked for me:

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