3

I have a controller action that checks

this.User.Identity.IsAuthenticated

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

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404

1 Answers1

5

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

Scott Lawrence
  • 6,993
  • 12
  • 46
  • 64
womp
  • 115,835
  • 26
  • 236
  • 269