Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 618
maz Avatar asked Dec 14 '08 10:12

maz


People also ask

Is it possible to unit test an MVC application without running the controllers in an ASP NET process?

thanks! unit tests do not run in the "MVC environment." They will run within the scope of the test runner, be that nunit, resharper,....

How does MVC know which controller to use?

Also, MVC relies heavily on reflection, which allows you to inspect types at runtime using strings. Reflection is used in many programming frameworks.


1 Answers

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 :-)).

like image 184
Darin Dimitrov Avatar answered Oct 20 '22 00:10

Darin Dimitrov