Hi i’m doing some unit test on my ASP.Net MVC2 project. I’m using Moq framework. In my LogOnController,
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl = "")
{
FormsAuthenticationService FormsService = new FormsAuthenticationService();
FormsService.SignIn(model.UserName, model.RememberMe);
}
In FormAuthenticationService class,
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 executing
FormsService.SignIn(model.UserName, model.RememberMe);
this line. Or is there any way to Moq
FormsService.SignIn(model.UserName, model.RememberMe);
using Moq framework without changing my ASP.Net MVC2 project.
Inject
IFormsAuthenticationServiceas a dependency to yourLogOnControllerlike thisThe first constructor is for the framework so that the correct instance of
IFormsAuthenticationServiceis used at runtime.Now in your tests create an instance of
LogonControllerusing the other constructor by passing mock as belowChange your action code to use the private field
formsAuthenticationServiceas belowHope this helps. I have left out the mock setup for you. Let me know if you are not sure how to set that up.