ASP.NET MVC Unit testing action methods which uses Session variables
In ASP.NET MVC, Unit testing action methods which uses Session variables is not an easy thing to do. We can use some mocking libraries to handle this. Here is an example to do that with RhinoMocks library
You need to add a reference to RhinoMocks library and import the Rihno.Mocks namespace to your class with a "using" statement.
The below example is for testing the Index
action method of ProjectController
which returns a list of projects to the user in the view. The action method calls the GetProjects
method available in the Repository to get data where it has to pass the "TeamID" which is stored in the Session variable for some reason.
//Arrange const int fakeTeamID = 1; var _session = MockRepository.GenerateStrictMock<HttpSessionStateBase>(); _session.Stub(s => s["TB_TeamID"]).Return(fakeTeamID); var _context = MockRepository.GenerateStrictMock<HttpContextBase>(); _context.Stub(c => c.Session).Return(_session); var projectList = new List<Project>(); projectList.Add(new Project { ID = 1, Name = "TeamBins", TeamID = fakeTeamID }); projectList.Add(new Project { ID = 2, Name = "kTable", TeamID = fakeTeamID }); var repository = MockRepository.GenerateStrictMock<IRepositary>(); repository.Stub(s => s.GetProjects(Arg<int>.Is.Anything)).Return(projectList); ProjectController projCntrl = new ProjectController(repository); projCntrl.ControllerContext = new ControllerContext(_context, new RouteData(), projCntrl); //Act var result = projCntrl.Index() as ViewResult; var resultModel = result.Model as ProjectListVM; //Now you may assert whatever you want here
Assuming IRepositary has a GetProjects
method which returns a list of Project objects for the TeamID passed.