Unit Testing a Controller which uses ISession

I had some fair issues with getting values from the HttpContext.Session, so here goes!

The method GetId on the FooController:

public IActionResult GetId()
  int fooId = HttpContext.Session.Get<int>(Foo)
  return json(fooId);

So, the trick was to mock the Get method of Session.
Here is my Unit Test using xUnit and Moq

The test:

public void GetId_AllGood_ReturnInt()
  Mock<ISession> sessionMock = new Mock<ISession>();

  Web.Controllers.FooController fooController = new Web.Controllers.FooController();
  fooController.ControllerContext.HttpContext = new DefaultHttpContext();
  fooController.ControllerContext.HttpContext.Request.Headers["Foo"] = 0; 
  fooController.ControllerContext.HttpContext.Session = sessionMock.Object;

  var result = fooController.GetFoos() as JsonResult;


You have to set the Headers you want to use on your Session and set the Session to a mocked ISession and you are good to go!

Leave a Reply