【问题标题】:FormsAuthentication.SetAuthCookie mocking using Moq使用 Moq 模拟 FormsAuthentication.SetAuthCookie
【发布时间】:2012-07-09 13:15:07
【问题描述】:

您好,我正在对我的 ASP.Net MVC2 项目进行一些单元测试。我正在使用 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 项目。

【问题讨论】:

  • 什么是 SUT(被测系统) - LogOnControllerFormsAuthenticationService?如果是前者,则应该为FormsAuthenticationService 提供一个假的,并且您应该验证它是否调用了SignIn 方法。后者更难进行单元测试,因为它需要一个当前的HttpContext 来添加一个cookie(到HttpResponse)。
  • 我想测试 LogOnController。我试图模拟 FormsService.SignIn(model.UserName, model.RememberMe);这样, var formService=new Mock();但是 formservice.SignIn 不返回任何内容。如何避免执行该行或如何模拟该行。我不知道如何使用 Moq 来模拟它。

标签: c# unit-testing asp.net-mvc-2 moq


【解决方案1】:

像这样将IFormsAuthenticationService 作为LogOnController 的依赖项注入

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

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

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

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

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

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

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

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

【讨论】:

  • 谢谢苏哈斯。我不知道把这段代码放在哪里,因为我是 ASP.Net u=Unit testing 的新手。你的意思是我应该在 mvc 项目中更改我的 LogOnController 吗?请善意解释。提前致谢。
  • 我希望你现在清楚了。如果您仍然遇到此问题,请告诉我。
  • 我按照给定的步骤操作。出现了一些错误,我可以解决。它有效。真的很感谢你的好意。谢谢。
猜你喜欢
  • 2011-06-13
  • 2019-09-11
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多