How can I unit test my ASP.NET MVC controller that uses FormsAuthentication?

前端 未结 1 983
臣服心动
臣服心动 2020-12-23 19:47

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 wit

相关标签:
1条回答
  • 2020-12-23 20:10

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

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

    0 讨论(0)
提交回复
热议问题