Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking HttpContext doesn't work

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?

like image 214
VolkanUzun Avatar asked Oct 27 '08 04:10

VolkanUzun


1 Answers

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);
like image 195
Tim Scott Avatar answered Oct 20 '22 07:10

Tim Scott