2012-07-09 80 views
7

嗨,我正在做我的ASP.Net MVC2项目的单元测试。我正在使用Moq框架。在我LogOnController,FormsAuthentication.SetAuthCookie使用Moq嘲弄

[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); 

此行。或者是有什么办法使用起订量框架没有改变我的ASP.Net MVC2项目,起订量

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

+0

什么是SUT(被测系统) - LogOnController或FormsAuthenticationService?如果它是前者,则应该为'FormsAuthenticationService'提供一个伪造品,并且应该验证是否调用了SignIn'方法。后者很难单元测试,因为它需要一个当前的'HttpContext'来添加一个cookie(到'HttpResponse')。 – 2012-07-09 13:37:02

+0

我想测试LogOnController。我试图模拟FormsService.SignIn(model.UserName,model.RememberMe); 以这种方式, var formService = new Mock (); 但formservice.SignIn不返回任何内容。我该如何避免执行该行或如何嘲笑该行。我不知道如何使用Moq来模拟。 – Dilma 2012-07-10 04:43:43

回答

9

进样IFormsAuthenticationService作为依赖于你的LogOnController这样

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

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

第一个构造是,这样的IFormsAuthenticationService正确的实例在运行时使用的框架。

在您的测试

现在,通过将模拟如下

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

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

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

希望这会创建使用其他构造函数的LogonController实例帮助。我已经为你省去了模拟设置。如果你不确定如何设置,请告诉我。

+0

谢谢Suhas。我不知道该把代码放在哪里,因为我是ASP.Net的新手u =单元测试。你的意思是我应该改变我的LogOnController在mvc项目中?请善待解释。提前致谢。 – Dilma 2012-07-10 04:53:52

+0

谢谢..它的工作..谢谢你Suhas。 – Dilma 2012-07-10 06:12:58

+0

我希望你现在很清楚。让我知道你是否仍然面临这个问题。 – Suhas 2012-07-10 08:05:53