如何在FakeHttpContext中设置Request.Header以进行单元测试 [英] How to setup Request.Header in FakeHttpContext for Unit Testing

查看:212
本文介绍了如何在FakeHttpContext中设置Request.Header以进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 FakeHttpContext ,我一直在尝试修改以包含一些标头以进行测试

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;
 }

这在没有标题的情况下有效,但是当我在 httpRequest stringWriter 行之间添加任何这些代码行时.

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";

抛出

发生类型为'System.PlatformNotSupportedException'的异常 在System.Web.dll中,但未在用户代码中处理

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

  • 为什么我会收到该例外?
  • 是否可以将标头添加到 HttpContext 进行测试 WebApi控制器?
    • Why am I getting that exception?
    • Is there a possible way to add headers to HttpContext for testing WebApi controllers?
    • 推荐答案

      我刚刚发现,使用 HttpRequestMessage类,您可以轻松添加标头来测试 WebAPI控制器,而无需必须创建任何伪造 HttpContext .

      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;
      

      这篇关于如何在FakeHttpContext中设置Request.Header以进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆