vijaykud
vijaykud

Reputation: 25

Hot to Add Cookies to the httpcontextbase from unit test and accessing from controller

I am trying to unit test one of my controller action method but having issue with HttpContext.

Below is the Action method code which reads the id from the cookie.

 public decimal GetId()
    {
        string result = "0"; 
        try
        {
        HttpCookie authCookie = HttpContext.Request.Cookies["Id"];
     //Getting error in above line of code saying the Httpcontext is null
        FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);
              result = ticket.UserData.Substring(0, ticket.UserData.IndexOf("|"));

        }
        catch (Exception ex)
        {
            LoggerHelper.LogError("GetID", ex.ToString());
        }

        return Convert.ToDecimal(result);
    }

And when I try to unit test the controller Action method getting error in below line of code

   HttpCookie authCookie = HttpContext.Request.Cookies["Id"];

HttpContext becoming null even though I fake the httpcontextbase and added cookie to it in my Unit test code.

Please help. I spent whole day but still unable to figure it out why HttpContext becoming null.

Thanks in advance, VJ

Upvotes: 1

Views: 1170

Answers (2)

user3675847
user3675847

Reputation: 51

Try this:

private static IRequestCookieCollection MockRequestCookieCollection(string key, string value)
    {
        var requestFeature = new HttpRequestFeature();
        var featureCollection = new FeatureCollection();

        requestFeature.Headers = new HeaderDictionary();
        requestFeature.Headers.Add(HeaderNames.Cookie, new StringValues(key + "=" + value));

        featureCollection.Set<IHttpRequestFeature>(requestFeature);

        var cookiesFeature = new RequestCookiesFeature(featureCollection);

        return cookiesFeature.Cookies;
    }

Upvotes: 2

vijaykud
vijaykud

Reputation: 25

Solved the problem by using

System.Web.HttpContext.Current.Request.Cookies["Id"];

instead of using

HttpContext.Request.Cookies["Id"];

in controller, since I am creating the System.Web.Httpcontext in my unit test case.

Upvotes: 0

Related Questions