[英]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.我试图弄清楚如何测试一块 .NET 核心中间件。
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.我已经设置了一个单元测试,我需要将 HttpContext 传递给中间件。 The issue I have is that I don't seem to find a way to add a HttpRequest to the context.
我遇到的问题是我似乎没有找到将 HttpRequest 添加到上下文的方法。
[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. HttpContext 上的 Request 属性是只读的。 Is there another way to add a httpRequest to a context?
是否有另一种方法可以将 httpRequest 添加到上下文中?
Just set the properties on the context's request property.只需在上下文的请求属性上设置属性。 The
DefaultHttpContext
creates one by default DefaultHttpContext
默认创建一个
//...
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
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.