Mocking User.Identity in ASP.NET MVC

后端 未结 6 918
眼角桃花
眼角桃花 2020-12-13 06:23

I need to create Unit Tests for an ASP.NET MVC 2.0 web site. The site uses Windows Authentication.

I\'ve been reading up on the necessity to mock the HTTP context

6条回答
  •  长情又很酷
    2020-12-13 07:18

    I've used IoC to abstract this away with some success. I first defined a class to represent the currently logged in user:

    public class CurrentUser
    {
        public CurrentUser(IIdentity identity)
        {
            IsAuthenticated = identity.IsAuthenticated;
            DisplayName = identity.Name;
    
            var formsIdentity = identity as FormsIdentity;
    
            if (formsIdentity != null)
            {
                UserID = int.Parse(formsIdentity.Ticket.UserData);
            }
        }
    
        public string DisplayName { get; private set; }
        public bool IsAuthenticated { get; private set; }
        public int UserID { get; private set; }
    }
    

    It takes an IIdentity in the constructor to set its values. For unit tests, you could add another constructor to allow you bypass the IIdentity dependency.

    And then I use Ninject (pick your favorite IoC container, doesn't matter), and created a binding for IIdentity as such:

    Bind().ToMethod(c => HttpContext.Current.User.Identity);
    

    Then, inside of my controller I declare the dependency in the constructor:

    CurrentUser _currentUser;
    
    public HomeController(CurrentUser currentUser)
    {
        _currentUser = currentUser;
    }
    

    The IoC container sees that HomeController takes a CurrentUser object, and the CurrentUser constructor takes an IIdentity. It will resolve the dependencies automatically, and voila! Your controller can know who the currently logged on user is. It seems to work pretty well for me with FormsAuthentication. You might be able to adapt this example to Windows Authentication.

提交回复
热议问题