How to setup Request.Header in FakeHttpContext for Unit Testing

别等时光非礼了梦想. 提交于 2020-01-14 07:58:06

问题


I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes

public static HttpContext FakeHttpContext()
{
    var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
    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);

    httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                        BindingFlags.NonPublic | BindingFlags.Instance,
                                        null, CallingConventions.Standard,
                                        new[] { typeof(HttpSessionStateContainer) },
                                        null)
                                .Invoke(new object[] { sessionContainer });

    return httpContext;
 }

This works without the headers but when I add any of these lines of code in between the httpRequest and stringWriter lines.

    httpRequest.Headers.Add("blah", "1234");
    httpRequest.Headers["blah"] = "1234";

It throws

An exception of type 'System.PlatformNotSupportedException' occurred in System.Web.dll but was not handled in user code

  • Why am I getting that exception?
  • Is there a possible way to add headers to HttpContext for testing WebApi controllers?

回答1:


I just discovered that with HttpRequestMessage class, you can easily add headers for testing your WebAPI controllers without having to create any fake HttpContext.

var request = new HttpRequestMessage(HttpMethod.Get, "http://stackoverflow");
request.Headers.Add("deviceId","1234");
_myController.Request = request;


来源:https://stackoverflow.com/questions/30909943/how-to-setup-request-header-in-fakehttpcontext-for-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!