C# FormsAuthentication.SetAuthCookie使用Moq模拟

C# FormsAuthentication.SetAuthCookie使用Moq模拟,c#,unit-testing,asp.net-mvc-2,moq,C#,Unit Testing,Asp.net Mvc 2,Moq,嗨,我正在对我的ASP.NETMVC2项目进行单元测试。我正在使用Moq框架。在我的LogOnController中 [HttpPost] public ActionResult LogOn(LogOnModel model, string returnUrl = "") { FormsAuthenticationService FormsService = new FormsAuthenticationService(); FormsService.SignIn(model.UserN

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

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

 }
在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();
        }
    }
我的问题是如何避免执行

FormsService.SignIn(model.UserName, model.RememberMe);
这条线。或者有没有办法去最低起订量

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

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

注入
IFormsAuthenticationService
作为对
登录控制器的依赖项,如下所示

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

public LogOnController(IFormsAuthenticationService formsAuthenticationService) : this(new FormsAuthenticationService())
{
    this.formsAuthenticationService = formsAuthenticationService;
}
第一个构造函数用于框架,以便在运行时使用
IFormsAuthenticationService
的正确实例

现在,在测试中,通过传递mock,使用另一个构造函数创建
LogonController
的实例,如下所示

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

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

什么是SUT(测试中的系统)
LogOnController或
FormsAuthenticationService
?如果是前者,则应为
FormsAuthenticationService
提供一个假的,并且您应验证是否对其调用了
SignIn
方法。后者更难进行单元测试,因为它需要一个当前的
HttpContext
,向其中添加cookie(到
HttpResponse
)。我试图模仿FormsService.SignIn(model.UserName,model.RememberMe);这样,var formService=newmock();但是formservice.sign不会返回任何内容。如何避免执行该行或如何模拟该行。我不知道如何用最小起订量来嘲笑它。谢谢Suhas。我不知道把这段代码放在哪里,因为我是ASP.NETU=单元测试的新手。你是说我应该在mvc项目中更改LogOnController吗?请解释一下。提前谢谢。我希望你现在明白了。如果您仍然面临此问题,请告诉我。我按照给定的步骤进行了操作。出现了一些错误,我可以处理。这很有效。非常感谢您的好意。非常感谢。
[HttpPost]
public ActionResult LogOn(LogOnModel model, string returnUrl = "")
{
    formsAuthenticationService.SignIn(model.UserName, model.RememberMe);
}