且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-17 07:44:53

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

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 :-)).