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 ?