Monday, March 10, 2014

Moling HttpContext and Session in unit test

Code to mockup the HttpSessionState object, this would call the mole in place of httpsession and context.

using System.Web;
using System.Web.Moles;
using System.Web.SessionState;
using System.Web.SessionState.Moles;
using Microsoft.Moles.Framework;

 [TestClass]
    public class RoleTests
    {
        Dictionary sessionState = new Dictionary();

        [TestInitialize]
        public void Setup()
        {
            MHttpContext ct = new MHttpContext
            {
                SessionGet = () => new MHttpSessionState
                {
                    ItemGetString = (key) =>
                    {
                        if (key == "Roles")
                        {
                            if (sessionState.Count == 0)
                            {
                                sessionState[key] = new List();
                            }

                            return sessionState[key];
                        }
                        else return null;
                    }
                }
            };

            MHttpContext.CurrentGet = () =>
            {
                return ct;
            };
        }

}