maz*_*maz 47 tdd asp.net-mvc unit-testing forms-authentication mocking
我正在以测试驱动的方式使用ASP.NET MVC解决方案,我想使用表单身份验证将用户登录到我的应用程序.我想在控制器中得到的代码看起来像这样:
FormsAuthentication.SetAuthCookie(userName, false);
我的问题是如何编写测试来证明这段代码的合理性?
有没有办法检查使用正确的参数调用SetAuthCookie方法?
有没有办法注入假/模拟FormsAuthentication?
Dar*_*rov 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保证:-)).
| 归档时间: | 
 | 
| 查看次数: | 11598 次 | 
| 最近记录: |