views:

173

answers:

2

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 for code that deals with the HttpContext. I feel like I'm starting to get a handle on the DI pattern as well. (Give the class an attribute of type IRepository and then pass in a Repository object when you instantiate the controller.)

What I don't understand, however, is the proper way to Mock the Windows Principal object available through User.Identity. Is this part of the HttpContext?

Does any body have a link to an article that demonstrates this (or a recommendation for a book)?

Thanks,

Trey Carroll

+3  A: 

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<IIdentity>().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 viola! 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.

John Nelson
+1  A: 

Scott Hanselman shows in his blog how to use IPrincipal and ModelBinder to make easier to test the controller by mocking IPrincipal.

Soe Moe