mardi 29 septembre 2015

How to perform Form Authentication testing in C# MVC 5.0

I have tried a lot and searched about. I got very few links about that but i am not succeeded in solving this problem.

With out generation any dummy form-authentication , In Unit Testing(c#-mvc) project I want to perform form-authentication.

I have used interface methods like below

    private readonly IAuthenticationProvider _authenticationProvider

    public AccountController(IAuthenticationProvider authenticationProvider)
    {
        _authenticationProvider = authenticationProvider;
    }

    public interface IAuthenticationProvider
    {
        void SignOut();
        void SetAuthCookie(string username, bool remember);
        void RedirectFromLoginPage(string username, bool createPersistentCookie);
    }


    public class FormsAuthWrapper : IAuthenticationProvider
    {
        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }
        public void SetAuthCookie(string username, bool remember)
        {
            FormsAuthentication.SetAuthCookie(username, remember);
        }
        public void RedirectFromLoginPage(string username, bool createPersistentCookie)
        {
            FormsAuthentication.RedirectFromLoginPage(username, createPersistentCookie);
        }
    }

For login

   public ActionResult Login(LoginViewModel model, string returnurl)
   {
      _authenticationProvider.SetAuthCookie(model.username, false)
   }

Is any other way to initialize form-authentication object. I am still getting error : Object reference not set to an instance of an object.

Because _authenticationProvider is null and form-authentication is not initialized

It says Use new keyword to create an object Instance

StackTrace is following..

   at System.Web.Security.CookielessHelperClass.UseCookieless(HttpContext context, Boolean doRedirect, HttpCookieMode cookieMode)
   at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie, String strCookiePath)
   at System.Web.Security.FormsAuthentication.SetAuthCookie(String userName, Boolean createPersistentCookie)
   at Test.Controllers.AccountController.Login(LoginViewModel model, String returnurl) in d:\projects\Test\Test\Controllers\AccountController.cs:line 81
   at Test.Tests.Controllers.CIControllerTest.TestSetup() in d:\projects\Test\Test.Tests\Controllers\CIControllerTest.       cs:line 47

Aucun commentaire:

Enregistrer un commentaire