Search code examples
c#unit-testingmockinghttprequesthttpsession

Getting null in HttpSessionStateBase c# unit test


While running my unit test method, I am getting null values in instance of HttpSessionStateBase. I have mocked the httpcontext like this

var httpRequest = new HttpRequest("", "http://localhost/", "");
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);

Please suggest some ideas to get some dummy values in HttpSessionStateBase


Solution

  • Let's suppose that you have the following controller action that you need to unit test:

    public class AccountController: Controller
    {
        public ActionResult Login(Customer obj)
        {
            Session.Clear();
            return View();
        }
    }
    

    and here's a sample wire-up:

    // arrange
    var httpRequest = new HttpRequest("", "http://localhost/", "");
    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);
    
    var controller = new AccountController();
    var requestContext = new RequestContext(new HttpContextWrapper(httpContext), new RouteData());
    controller.ControllerContext = new ControllerContext(requestContext, controller);
    
    // act
    var actual = controller.Login(new Customer());
    
    // assert
    ...
    

    Notice that you need to populate the controller.ControllerContext property before calling the actions.