我单位如何测试使用FormsAuthentication我的ASP.NET MVC控制器? [英] How can I unit test my ASP.NET MVC controller that uses FormsAuthentication?

查看:104
本文介绍了我单位如何测试使用FormsAuthentication我的ASP.NET MVC控制器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在测试驱动方式ASP.NET MVC解决方案时,我想使用窗体身份验证对用户登录到我的应用程序。在code,我想最终在控制器看起来是这样的:

I'm working with a ASP.NET MVC solution in a test driven manner and I want to login a user to my application using forms authentication. The code I would like to end up with in the controller looks something like this:

FormsAuthentication.SetAuthCookie(userName, false);

我的问题是我怎么写一个测试,以证明这一code?

My question is how do I write a test to justify this code?

有没有一种方法来检查SetAuthCookie方法调用了正确的参数?

Is there a way to check that the SetAuthCookie method was called with the correct parameters?

有注射假/模拟FormsAuthentication的方法吗?

Is there any way of injecting a fake/mock FormsAuthentication?

推荐答案

我会写一个接口和一个包装类,将封装这一逻辑,然后使用该接口在我的控制器启动:

I would start by writing an interface and a wrapper class that will encapsulate this logic and then use the interface in my controller:

public interface IAuth 
{
    void DoAuth(string userName, bool remember);
}

public class FormsAuthWrapper : IAuth 
{
    public void DoAuth(string userName, bool remember) 
    {
        FormsAuthentication.SetAuthCookie(userName, remember);
    }
}

public class MyController : Controller 
{
    private readonly IAuth _auth;

    public MyController(IAuth auth) 
    {
        _auth = auth;
    }

}

现在 IAuth 可以很容易地在单元测试嘲笑,并验证控制器调用就可以了预期的方法。我不会单元测试 FormsAuthWrapper 类,因为它只是代表在调用 FormsAuthentication 这做什么它应该做的。(微软保证: - ))

Now IAuth could be easily mocked in a unit test and verify that the controller calls the expected methods on it. I would NOT unit test the FormsAuthWrapper class because it just delegates the call to the FormsAuthentication which does what it is supposed to do (Microsoft guarantee :-)).

这篇关于我单位如何测试使用FormsAuthentication我的ASP.NET MVC控制器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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