0

We have the following lines in one of the functions in the MVC controller.

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

In my unit test, I am calling this controller to test.

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

My test case fails because there is no value in the HttpContext for empPermission during the runtime.

We are wondering how can we populate the HttpContext.Items with a value so it can pick up during the runtime. We have look for some examples in mock, but not any luck so far.

CodeNotFound
  • 18,731
  • 6
  • 54
  • 63
ggk
  • 1
  • 2
  • This question is incomplete and wont compile. Provide a [mcve] that can be used to reproduce the problem. Maybe then better help can be provided. – Nkosi Apr 29 '17 at 00:19
  • Possible duplicate of [How do I mock the HttpContext in ASP.NET MVC using Moq?](http://stackoverflow.com/questions/1452418/how-do-i-mock-the-httpcontext-in-asp-net-mvc-using-moq) – ctyar Apr 29 '17 at 10:28

1 Answers1

0

You need to mock the HttpContext. Here is an example of code that should run in your unit test (preferably on TestInitialize) before calling your controller method:

    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]

Possible repeat of Mock HttpContext.Current in Test Init Method

Community
  • 1
  • 1
Kevin Raffay
  • 833
  • 5
  • 18