Robert Koritnik
Robert Koritnik

Reputation: 105081

Unit testing an Asp.net MVC controller action

I have a controller action that checks

this.User.Identity.IsAuthenticated

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

Upvotes: 3

Views: 951

Answers (1)

womp
womp

Reputation: 116987

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 suggest looking into Scott Hanselman's ubiquitous "MvcMockHelpers" code, which is what I use:

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

Upvotes: 5

Related Questions