I am trying to use Rhino.Mocks to mock up a ControllerContext object to gain access to runtime objects like User, Request, Response, and Session in my controller unit tests. I’ve written the below method in an attempt to mock up a controller.
private TestController CreateTestControllerAs(string userName)
{
var mock = MockRepository.GenerateStub<ControllerContext>();
mock.Stub(con =>
con.HttpContext.User.Identity.Name).Return(userName);
mock.Stub(con =>
con.HttpContext.Request.IsAuthenticated).Return(true);
var controller = CreateTestController(); // left out of example for brevity
controller.ControllerContext = mock;
return controller;
}
However, the HttpContext of my mocked ControllerContext is null and there my attempts to access HttpContext.User etc. cause a System.NullReferenceException.
What am I doing wrong with my mocking?
I would strongly recommend you looking at MVCContrib.TestHelper which uses
Rhino.Mocksand provides an elegant way to test your controllers. Here’s how your test might look like:And here’s an unit test for a controller that is part of a sample ASP.NET MVC application I wrote.