如何对使用FormsAuthentication的ASP.NET MVC控制器进行单元测试?

时间:2008-12-14 10:48:08

标签: asp.net-mvc unit-testing tdd mocking forms-authentication

我正在以测试驱动的方式使用ASP.NET MVC解决方案,我想使用表单身份验证将用户登录到我的应用程序。我想在控制器中得到的代码看起来像这样:

FormsAuthentication.SetAuthCookie(userName, false);

我的问题是我如何编写测试来证明这段代码的合理性?

有没有办法检查是否使用正确的参数调用了SetAuthCookie方法?

有没有办法注入假/模拟FormsAuthentication?

1 个答案:

答案 0 :(得分:68)

我首先编写一个接口和一个封装类,它将封装这个逻辑,然后在我的控制器中使用该接口:

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来执行它应该做的事情(Microsoft保证: - ))。