mercredi 14 septembre 2016

How Mock Cookie in Uni 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://ift.tt/2cbsYvW";
            var server = new HttpServer(new HttpConfiguration(), fakeResponseHandler);
            var httpClient = new HttpClient(server);
            var controller = new LoanDriverController(httpClient);
            Fake.SetFakeAuthenticatedControllerContext(controller);
            var result = controller.Login(request);
            Assert.IsNotNull(result);
        }

Aucun commentaire:

Enregistrer un commentaire