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 ?
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
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With