FormsAuthentication.SetAuthCookie Taunts Using Moq

Hi, I am doing a few unit test in my ASP.Net MVC2 project. I use the Moq framework. In my LogOnController,

[HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl = "") { FormsAuthenticationService FormsService = new FormsAuthenticationService(); FormsService.SignIn(model.UserName, model.RememberMe); } 

In class FormAuthenticationService

 public class FormsAuthenticationService : IFormsAuthenticationService { public virtual void SignIn(string userName, bool createPersistentCookie) { if (String.IsNullOrEmpty(userName)) throw new ArgumentException("Value cannot be null or empty.", "userName"); FormsAuthentication.SetAuthCookie(userName, createPersistentCookie); } public void SignOut() { FormsAuthentication.SignOut(); } } 

My problem is how can I avoid execution

 FormsService.SignIn(model.UserName, model.RememberMe); 

this line. Or is there any way to moq

  FormsService.SignIn(model.UserName, model.RememberMe); 

using a Moq frame without modifying my ASP.Net MVC2 project.

+7
source share
1 answer

Inject IFormsAuthenticationService as a dependency on your LogOnController like this

 private IFormsAuthenticationService formsAuthenticationService; public LogOnController() : this(new FormsAuthenticationService()) { } public LogOnController(IFormsAuthenticationService formsAuthenticationService) : this(new FormsAuthenticationService()) { this.formsAuthenticationService = formsAuthenticationService; } 

The first constructor for the framework, so that the correct instance of IFormsAuthenticationService is used at run time.

Now in your tests create an instance of LogOnController using another constructor, skipping mock as below

 var mockformsAuthenticationService = new Mock<IFormsAuthenticationService>(); //Setup your mock here 

Modify the action code to use the formsAuthenticationService private field, as shown below

 [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl = "") { formsAuthenticationService.SignIn(model.UserName, model.RememberMe); } 

Hope this helps. I have given up on the layout for you. Let me know if you do not know how to install it.

+9
source

All Articles