FormsAuthentication.SetAuthCookie使用Moq进行模拟

Dil*_*lma 8 c# unit-testing moq asp.net-mvc-2

嗨,我正在对我的ASP.Net MVC2项目进行一些单元测试.我正在使用Moq框架.在我的LogOnController中,

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

 }
Run Code Online (Sandbox Code Playgroud)

在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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

我的问题是如何避免执行

FormsService.SignIn(model.UserName, model.RememberMe);
Run Code Online (Sandbox Code Playgroud)

这条线.或者有没有办法去Moq

 FormsService.SignIn(model.UserName, model.RememberMe);
Run Code Online (Sandbox Code Playgroud)

使用Moq框架而不更改我的ASP.Net MVC2项目.

Suh*_*has 10

IFormsAuthenticationService作为对LogOnController此类的依赖注入

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

public LogOnController(IFormsAuthenticationService formsAuthenticationService) : this(new FormsAuthenticationService())
{
    this.formsAuthenticationService = formsAuthenticationService;
}
Run Code Online (Sandbox Code Playgroud)

第一个构造函数用于框架,以便IFormsAuthenticationService在运行时使用正确的实例.

现在,在您的测试中,LogonController通过传递mock来创建使用其他构造函数的实例,如下所示

var mockformsAuthenticationService = new Mock<IFormsAuthenticationService>();
//Setup your mock here
Run Code Online (Sandbox Code Playgroud)

更改您的操作代码以使用私有字段formsAuthenticationService,如下所示

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

希望这可以帮助.我已经为你省略了模拟设置.如果您不确定如何设置,请告诉我.