Mocking HttpContext doesn't work

asp.net, asp.net-mvc, mocking, rhino-mocks, unit-testing

Solution

This should work:

PostsController postsController = new PostsController(postDL);
var context = mocks.Stub<HttpContextBase>();
var request = mocks.Stub<HttpRequestBase>();
SetupResult.For(request.IsAuthenticated).Return(true);
SetupResult.For(context.Request).Return(request);    
postsController.ControllerContext = new ControllerContext(context, new RouteData(), postsController);

Problem

I am trying to mock out HttpContext so that I can unit test my controller's Request.IsAuthenicated call. I am using the code that I found at Scott Hanselman's blog to simulate HttpContext using rhino.mocks. so i have this unit test piece: ``` PostsController postsController = new PostsController(postDL); mocks.SetFakeControllerContext(postsController); Expect.Call(postsController.Request.IsAuthenticated).Return(true); ``` In my controller action, I have something like `if(Request.IsAuthenticated)....` when I try to run the unit test, the test fails throwing a null exception, and when I try to debug the unit test, I see that the HttpContext is never assigned to the controller. any ideas?

Original source