Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit test MiddleWare, how to add a HttpRequest to a HttpContext in .NET Core 3.1

I trying to get my head around how to test a piece of .NET Core middleware.

public class MyMiddleware
    {
    public async Task Invoke(HttpContext context) {
    
      var requestProperties = GetPropertiesFromRequest(context.Request);
    } 
    
    public string GetPropertiesFromRequest(HttpRequest request) {
      //do stuff with request
    }
}

I've set up a unit test where I need to pass a HttpContext to the middleware. The issue I have is that I don't seem to find a way to add a HttpRequest to the context.

    [Fact]
    public async Task Middleware_should_get_properties_from_request()
    {
        var request = new HttpRequestMessage()
        {
            Method = HttpMethod.Get,
            RequestUri = new Uri("https://localhost:5001/"),
            Content = new StringContent({ 'message':'some content'}, Encoding.UTF8, "application/json"),
        };

    HttpContext context = new DefaultHttpContext();
    //context.Request = request;  //how to set the request on the context ?

     var myMiddleware = new MyMiddleware();
     await myMiddleware.Invoke(context);

     //Assert properties 
 }

The Request property on HttpContext is read-only. Is there another way to add a httpRequest to a context ?

like image 994
Oysio Avatar asked Dec 31 '25 08:12

Oysio


1 Answers

Just set the properties on the context's request property. The DefaultHttpContextcreates one by default

//...

var httpContext = new DefaultHttpContext();

var json = JsonConvert.SerializeObject("{ 'message':'some content'}");
var stream = new MemoryStream(Encoding.UTF8.GetBytes(json));
httpContext.Request.Body = stream;

httpContext.Request.ContentLength = stream.Length;
httpContext.Request.ContentType = "application/json";

 var myMiddleware = new MyMiddleware();

//Act
await myMiddleware.Invoke(httpContext);

//Assert
//...
like image 188
Nkosi Avatar answered Jan 02 '26 20:01

Nkosi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!