views:

244

answers:

1

I have a controller action that checks

this.User.Identity.IsAuthenticated

What do you suggest how to tackle unit test on such an action?

+4  A: 

I would suggest mocking the IsAuthenticated property. There are a number of other posts on SO about this, you could do a search for them.

Here is an example of mocking the request using Moq:

var mockRequest = new Mock<HttpRequestBase>();
mockRequest.Setup(x => x.IsAuthenticated).Returns(true); 

var mockContext = new Mock<ControllerContext>();
mockContext.Setup(x => x.Request).Returns(mockRequest.Object);

var myController = new MyController();
myController.ControllerContext = new ControllerContext(mockContext.Object, new RouteData(), myController);

I would highly suggets looking into Scott Hanselmann's ubiqtuous "MvcMockHelpers" code, which is what I use:

http://www.hanselman.com/blog/ASPNETMVCSessionAtMix08TDDAndMvcMockHelpers.aspx

womp
But how would you inject your mocked HttpContext/Request? User property is part of Controller class and has it's own code I can't influence.
Robert Koritnik
Ok. Now your code has the answer. The ControllerContext property I wasn't aware of. Thanks.
Robert Koritnik
In Moq you are using SetupGet for mocking properties (Setup is only for mocking methods)
eu-ge-ne
Yes. Or even SetupProperty if it has both setter and getter with "memory"... ;) I know that. womp's code was enough for me to get the concept right.
Robert Koritnik