How to access HttpContext inside a unit test in ASP.NET 5 / MVC 6

后端 未结 4 2216

Lets say I am setting a value on the http context in my middleware. For example HttpContext.User.

How can test the http context in my unit test. Here is an example o

4条回答
  •  天涯浪人
    2020-12-25 08:46

    take a look at this post:

    Setting HttpContext.Current.Session in a unit test

    I think what you need is this.

    public static HttpContext FakeHttpContext(string url)
    {
        var uri = new Uri(url);
        var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                            uri.Query.TrimStart('?'));
        var stringWriter = new StringWriter();
        var httpResponse = new HttpResponse(stringWriter);
        var httpContext = new HttpContext(httpRequest, httpResponse);
    
        var sessionContainer = new HttpSessionStateContainer("id",
                                        new SessionStateItemCollection(),
                                        new HttpStaticObjectsCollection(),
                                        10, true, HttpCookieMode.AutoDetect,
                                        SessionStateMode.InProc, false);
    
        SessionStateUtility.AddHttpSessionStateToContext(
                                             httpContext, sessionContainer);
    
        return httpContext;
    }
    

    Then you can use it like:

    request.SetupGet(req => req.Headers).Returns(new NameValueCollection());
    HttpContextFactory.Current.Request.Headers.Add(key, value);
    

提交回复
热议问题