Avatar of purplesoup
purplesoup
Flag for United Kingdom of Great Britain and Northern Ireland asked on

How can I do Unit Testing with Session ?

I want to run a test to make sure the session object is getting updated with a particular key and value.

I've come across this:
http://stackoverflow.com/questions/9624242/setting-httpcontext-current-session-in-a-unit-test

which appears to offer at least three ways of achieving this, but each time I try the code out, I get a null reference error when assigning to the session object.

The test is something like this:
            var expected = "some value";
            using (var target = new MyControl())
            {
                var sut = new PrivateObject(target,new PrivateType(typeof(MyControl)));

                // set value
                sut.SetProperty("MyProperty", expected );
                Assert.Equals(expected , (string)HttpContext.Current.Session["MyKey"]);

Open in new window


The property is just basically
        private string MyProperty
        {
            get
            {
                return (string) Session["MyKey"]);
            }
            set
            {
                Session["MyKey"] = value;
            }
        }

Open in new window


Here are the three versions I tried:
        public static HttpContext FakeHttpContextv1()
        {
            var httpRequest = new HttpRequest("", "http://stackoverflow/", "");
            var stringWriter = new StringWriter();
            var httpResponse = new HttpResponse(stringWriter);
            var httpContext = new HttpContext(httpRequest, httpResponse);

            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                    new HttpStaticObjectsCollection(), 10, true,
                                                    HttpCookieMode.AutoDetect,
                                                    SessionStateMode.InProc, false);

            httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                        BindingFlags.NonPublic | BindingFlags.Instance,
                                        null, CallingConventions.Standard,
                                        new[] { typeof(HttpSessionStateContainer) },
                                        null)
                                .Invoke(new object[] { sessionContainer });

            return httpContext;
        }

        public static HttpContext FakeHttpContextv2()
        {
            var url = "http://localhost/";
            var uri = new Uri(url);
            var httpRequest = new HttpRequest(string.Empty, uri.ToString(),
                                                uri.Query.TrimStart('?'));
            var stringWriter = new StringWriter();
            var httpResponse = new HttpResponse(stringWriter);
            var httpContext = new HttpContext(httpRequest, httpResponse);

            var sessionContainer = new HttpSessionStateContainer("id",
                                            new SessionStateItemCollection(),
                                            new HttpStaticObjectsCollection(),
                                            10, true, HttpCookieMode.AutoDetect,
                                            SessionStateMode.InProc, false);

            SessionStateUtility.AddHttpSessionStateToContext(
                                                 httpContext, sessionContainer);

            return httpContext;
        }

        public static HttpContext FakeHttpContextv3()
        {
            // We need to setup the Current HTTP Context as follows:            

            // Step 1: Setup the HTTP Request
            var httpRequest = new HttpRequest("", "http://localhost/", "");

            // Step 2: Setup the HTTP Response
            var httpResponce = new HttpResponse(new StringWriter());

            // Step 3: Setup the Http Context
            var httpContext = new HttpContext(httpRequest, httpResponce);
            var sessionContainer =
                new HttpSessionStateContainer("id",
                                               new SessionStateItemCollection(),
                                               new HttpStaticObjectsCollection(),
                                               10,
                                               true,
                                               HttpCookieMode.AutoDetect,
                                               SessionStateMode.InProc,
                                               false);
            httpContext.Items["AspSession"] =
                typeof(HttpSessionState)
                .GetConstructor(
                                    BindingFlags.NonPublic | BindingFlags.Instance,
                                    null,
                                    CallingConventions.Standard,
                                    new[] { typeof(HttpSessionStateContainer) },
                                    null)
                .Invoke(new object[] { sessionContainer });

            // Step 4: Assign the Context
            return httpContext;
        }

Open in new window

ASP.NETC#.NET Programming

Avatar of undefined
Last Comment
purplesoup

8/22/2022 - Mon
ASKER CERTIFIED SOLUTION
purplesoup

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck