How can I unit test my ASP.NET MVC controller that uses FormsAuthentication?

I am working with an ASP.NET MVC solution in test mode and I want to log in to my application using forms authentication. The code I would like to get in the controller looks something like this:

FormsAuthentication.SetAuthCookie(userName, false); 

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

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

Is there any way to introduce fake / mock FormsAuthentication?

+46
unit-testing tdd asp.net-mvc mocking forms-authentication
Dec 14 '08 at 10:48
source share
1 answer

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 can be easily ridiculed in unit test and make sure that the controller calls the expected methods on it. I would not become the unit test class FormsAuthWrapper , because it simply delegates a call to FormsAuthentication , which does what it should do (Microsoft warranty: -)).

+65
Dec 14 '08 at 11:20
source share



All Articles