使用Moq进行FormsAuthentication.SetAuthCookie模拟 [英] FormsAuthentication.SetAuthCookie mocking using Moq

查看:111
本文介绍了使用Moq进行FormsAuthentication.SetAuthCookie模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

 }

在FormAuthenticationService类中,

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

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

using Moq framework without changing my ASP.Net MVC2 project.

推荐答案

IFormsAuthenticationService作为对您的LogOnController的依赖项注入

Inject IFormsAuthenticationService as a dependency to your LogOnController like this

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

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

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

The first constructor is for the framework so that the correct instance of IFormsAuthenticationService is used at runtime.

现在,在您的测试中,通过传递下面的模拟,使用其他构造函数创建LogonController的实例

Now in your tests create an instance of LogonController using the other constructor by passing mock as below

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

将操作代码更改为使用私有字段formsAuthenticationService,如下所示:

Change your action code to use the private field formsAuthenticationService as below

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

希望这会有所帮助.我没有为您设置模拟设置.如果您不确定如何设置,请告诉我.

Hope this helps. I have left out the mock setup for you. Let me know if you are not sure how to set that up.

这篇关于使用Moq进行FormsAuthentication.SetAuthCookie模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆