Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 212
Robert Koritnik Avatar asked Sep 09 '26 08:09

Robert Koritnik


1 Answers

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

like image 83
womp Avatar answered Sep 12 '26 07:09

womp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!