在MVC单元测试中填充HTTPContext.Item

时间:2017-04-28 23:33:29

标签: asp.net-mvc mocking httpcontext

我们在MVC控制器的其中一个函数中有以下几行。

public ActionResult EditEmp(int eId = 0)
{
    EPermission ePermission =  (EPermission)HttpContext.Items["empPermission"];
}

在我的单元测试中,我正在调用此控制器进行测试。

public void TestMethod1()
{
   var result = eController.EditEmp(10) as ViewResult;
}

我的测试用例失败,因为在运行时期间HttpContext empPermission没有值。

我们想知道如何使用值填充HttpContext.Items,以便它可以在运行时获取。我们在模拟中寻找一些例子,但到目前为止还没有运气。

1 个答案:

答案 0 :(得分:0)

你需要模拟HttpContext。以下是在调用控制器方法之前应在单元测试中运行的代码示例(最好是在TestInitialize上):

    var httpRequest = new HttpRequest("", "http://mySomething/", "");
    var stringWriter = new StringWriter();
    var httpResponce = new HttpResponse(stringWriter);
    var httpContext = new HttpContext(httpRequest, httpResponce);

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

    HttpContext.Current = httpContext;

    HttpContext.Current.User = new GenericPrincipal(
        new GenericIdentity("WSUSER"),
        new string[0]

可能重复Mock HttpContext.Current in Test Init Method