views:

1043

answers:

1

I'm working with a ASP.NET MVC solution in a test driven manner and I want to login a user to my application using forms authentication. The code I would like to end up with in the controller looks something like this:

FormsAuthentication.SetAuthCookie(userName, false);

My question is how do I write a test to justify this code?

Is there a way to check that the SetAuthCookie method was called with the correct parameters?

Is there any way of injecting a fake/mock FormsAuthentication?

+12  A: 

I would start by writing an interface and a wrapper class that will encapsulate this logic and then use the interface in my controller:

public interface IAuth 
{
    void DoAuth(string username, bool remember);
}

public class FormsAuthWrapper : IAuth 
{
    public void DoAuth(string username, bool remember) 
    {
        FormsAuthentication.SetAuthCookie(userName, remember);
    }
}

public class MyController : Controller 
{
    private readonly IAuth _auth;
    public MyController(IAuth auth) 
    {
        _auth = auth;
    }

}

Now IAuth could be easily mocked in a unit test and verify that the controller calls the expected methods on it. I would NOT unit test the FormsAuthWrapper class because it just delegates the call to the FormsAuthentication which does what it is supposed to do (Microsoft guarantee :-)).

Darin Dimitrov
+1 on this, don't test other people's frameworks, just YOUR usage of THEM. We do the same (similar) thing in our app (wrap FormsAuth stuff, etc)
chadmyers
*sigh* Microsoft is so proud of this framework being SO testable! I was hoping there was some built in way to mock this without wrapping. Guess not :(
maz