I have the following code in my controller action method:
if (User.Identity.IsAuthenticated)
{
// ...
}
It seems to work fine. But when I run a unit test that calls this action, it fails because User is null?
Can anyone suggest the best way to deal with this? Do I have to restructure this code just for unit tests?
You probably need to set the User property as part of your setup. You would do this by mocking the
HttpContextBaseviaControllerContextused to create the controller so that it returns your mocked user. Set your mockedControllerContextinto theControllerContextproperty, and it will findUserprovided you’ve configured the object graph correctly.