Alma
Alma

Reputation: 4420

How Mock Cookie in Unit test

I have a MVC controller that I am creating cookie in it and do the rest of operation. I need to unit test this method. I am not sure how to Mock the cookie.

This is my method in the controller:

public ActionResult Login(LogInRequest logInRequest)
{
    if (ModelState.IsValid)
    {
        HttpCookie usercookie = new HttpCookie("usercookie");
        usercookie["UserName"] = logInRequest.UserName;
        usercookie["Password"] = logInRequest.Password;
        usercookie.Expires = DateTime.Now.AddMinutes(10);
        **Response.Cookies.Add(usercookie);**
        return RedirectToAction("search", "LoanDriver");
        .......
        return View(logInRequest);
    }

in this line Response.Cookies.Add(usercookie); it gave me an error as Null. and when I trace the cookie has value.

And this is my test method:

public void Web_Login_ShouldValidateUserAndLoginSuccessfully()
{
    using (var kernel = new NSubstituteMockingKernel())
    {
        // Setup the dependency incjection
        kernel.Load(new EntityFrameworkTestingNSubstituteModule());

        // Create test request data 
        var request = new LogInRequest { UserName = "test", Password = "test" };
        var fakeResponseHandler = new FakeResponseHandler();
        fakeResponseHandler.AddFakeResponse(new Uri("http://localhost/test"), new HttpResponseMessage(HttpStatusCode.OK));
        ConfigurationManager.AppSettings["SearchApiBaseUrl"] = "http://dev.loans.carfinance.com/internal";
        var server = new HttpServer(new HttpConfiguration(), fakeResponseHandler);
        var httpClient = new HttpClient(server);
        var controller = new LoanDriverController(httpClient);
        Fake.SetFakeContext(controller);
        var result = controller.Login(request);
        Assert.IsNotNull(result);
    }
}

I have tried to add the cookie to Response as well but not working ans getting same issue:

public static void SetFakeContext(this Controller controller)
{
    var httpContext = InitialiseFakeHttpContext();
    ControllerContext context = 
        new ControllerContext(new RequestContext(httpContext, new RouteData()), controller);
    controller.ControllerContext = context;
}

private static HttpContextBase InitialiseFakeHttpContext(string url = "")
{ 
    var HttpContextSub = Substitute.For<HttpContextBase>();
    var RequestSub = Substitute.For<HttpRequestBase>();
    var ResponseSub = Substitute.For<HttpResponseBase>();
    var serverUtilitySub = Substitute.For<HttpServerUtilityBase>();
    var itemsSub = Substitute.For<IDictionary>();
    HttpContextSub.Request.Returns(RequestSub);
    HttpContextSub.Response.Returns(ResponseSub);
    HttpContextSub.Server.Returns(serverUtilitySub);
    var cookie = Substitute.For<HttpResponseBase>();
    HttpContextSub.Response.Returns(cookie);
    return HttpContextSub;
}

Upvotes: 1

Views: 7811

Answers (1)

Aldo
Aldo

Reputation: 304

I think you can handle this by doing some refactoring in your controller, per example, you can create an ICookieManager interface and a CookieManager class (this class contains the logic to add a cookie, also implements the ICookieManager Interface) then you could either add this ICookieManager as a dependency in your constructor or as a property and then you will be able to mock this dependency in your unit test, something like this :

public interface ICookieManager
    {
        void CreateUserCookie(string userName, string password, HttpResponseBase response, int expiration = 10);
    }

    public class CookieManager: ICookieManager
    {
        public void CreateUserCookie(string userName, string password, HttpResponseBase response, int expiration = 10)
        {
            HttpCookie usercookie = new HttpCookie("usercookie");
            usercookie["UserName"] = userName;
            usercookie["Password"] = password;
            usercookie.Expires = DateTime.Now.AddMinutes(expiration);
            response.Cookies.Add(usercookie);
        }
    }

In your controller :

 public class YourController : Controller
    {
        public ICookieManager CookieManager { get; set; }

        public YourController()
        {
            CookieManager = new CookieManager();
        }

        public YourController(ICookieManager cookieManager)
        {
            CookieManager = cookieManager;
        }

        public ActionResult Login(LogInRequest logInRequest)
        {
            if (ModelState.IsValid)
            {
                CookieManager.CreateUserCookie(logInRequest.UserName, logInRequest.Password, Response);
                return RedirectToAction("search", "LoanDriver");
            }
        }


    }

In your Unit Test:

public void Web_Login_ShouldValidateUserAndLoginSuccessfully()
    {
        using (var kernel = new NSubstituteMockingKernel())
        {
            // Setup the dependency incjection
            kernel.Load(new EntityFrameworkTestingNSubstituteModule());

            // Create test request data 
            var request = new LogInRequest { UserName = "test", Password = "test" };

            var fakeResponseHandler = new FakeResponseHandler();
            fakeResponseHandler.AddFakeResponse(new Uri("http://localhost/test"), new HttpResponseMessage(HttpStatusCode.OK));
            ConfigurationManager.AppSettings["SearchApiBaseUrl"] = "http://dev.loans.carfinance.com/internal";
            var server = new HttpServer(new HttpConfiguration(), fakeResponseHandler);
            var httpClient = new HttpClient(server);
            var controller = new LoanDriverController(httpClient);
            controller.CookieManager=mockOfYourCookieManager; //here you pass the instance of the mock or also you can passe it in the constructor of the controller.
            Fake.SetFakeContext(controller);
            var result = controller.Login(request);
            Assert.IsNotNull(result);
        }

Upvotes: 2

Related Questions