RSS
Giga Web Solution - Gaetano Santonastaso

Mock Session in MVC3 using Rhino Mock

Many times happened to me to have problems mocking the Session to test my Controllers in MVC projects, after many attempts the following is the best solution I've found so far.



Let's assume we have a controller that relies on the Session:

public class DatabaseExplorerController : Controller
{    
    private IRepository _repository;

    public DatabaseExplorerController(IRepository repository)
    {
        _repository = repository;
    }

    public string Connectionstring
    {
        get { return Session["Connectionstring"].ToString(); }
        set { Session["Connectionstring"] = value; }
    }

    public PartialViewResult Index()
    {
        var data = repository.GetData(Connection);

        return View("Index", data);
    }
}


In the test we can Mock the Session and the Context and pass them to the controller

_session = MockRepository.GenerateStrictMock<HttpSessionStateBase>();
_session.Stub(s => s["Connectionstring"]).Return(Connectionstring);

_context = MockRepository.GenerateStrictMock<HttpContextBase>();
_context.Stub(c => c.Session).Return(_session);

var databaseExplorerController = new DatabaseExplorerController(repository);

databaseExplorerController.ControllerContext = 
  new ControllerContext(_context, new RouteData(), _databaseExplorer);


Our test will look like

 
[Test]
public void DisplaytableShouldReturnTablePartialView()
{ 
   var repository = MockRepository.GenerateStrictMock<IRepository>();

  repository.Expect(r => r.GetData(Arg<string>.Is.Anything).Returns(string.Empty);

  var databaseExplorerController = new DatabaseExplorerController(repository);

  databaseExplorerController.ControllerContext = 
     new ControllerContext(_context, new RouteData(), _databaseExplorerController);

   var result = databaseExplorerController.Index();

   Assert.IsNotNull(result);
   Assert.AreEqual("Index", result.ViewName);
   Assert.IsInstanceOf<string>(result.ViewData.Model);
}



Jul17

Back To List