I am trying to unit test a razor view (MVC .NET). I want to test whether the user logged in’s name appears on the site. I am not sure how will I do this due to User.Identity.Name – this is a static object, so can’t be mocked.
Should this static object be set in the test? Is there a nicer way of doing this?
Thanks!
You could create create a ControllerContext with a mock HttpContext to return an IPrincipal to your liking. See this post on how to do that:
Mocking and HttpContextBase.get_User()
The example uses Rhino Mocks, but is easily adaptable to whatever mock framework you are using. Make sure that the fake IPrincipal.Identity.Name returns a string for the name. I can give you an example with FakeItEasy or Rhino Mocks if you think its not clear.
You can then assert that the user name placed in the ViewBag or in the ViewModel for your view is equal to the name you let your fake IIdentity return.