.Net, TDD

Stub HttpContext

Have you ever tried to TDD objects that use HttpContext, HttpResponse, or HttpRequest?  If you did, you probably created wrappers for these classes.  No more.  With .NET 3.5 Microsoft gave us System.Web.Abstractions.dll that extends System.Web namespace.  In this post I’d like to show an example how to stub HttpContext.

Here’s the system under test:

    public class MyContext
        private readonly HttpContextBase _context;

        // This constructor is called by production system.
        public MyContext() : this(new HttpContextWrapper(HttpContext.Current))

        // Test calls this constructor
        public MyContext(HttpContextBase context)
            _context = context;

        public bool IsItemCached(string item)
            return _context.Cache[item] != null;

Here are the unit tests:

    public class MyContextTester
        private HttpContextBase _contextStub;
        private MyContext _myContext;

        public void StartTest()
            _contextStub = MockRepository.GenerateMock<HttpContextBase>();
            _myContext = new MyContext(_contextStub);

        public void IsItemCached_if_Cache_item_is_null_return_false()
            _contextStub.Stub(x => x.Cache).Return(HttpRuntime.Cache);
            Assert.IsFalse(_myContext.IsItemCached("NotThere"), "False is expected.");

        public void IsItemCached_if_Cache_item_is_NOT_null_return_true()
            HttpRuntime.Cache.Insert("I am HERE", "value");
            _contextStub.Stub(x => x.Cache).Return(HttpRuntime.Cache);
            Assert.IsTrue(_myContext.IsItemCached("I am HERE"), "True is expected.");

kick it on DotNetKicks.com


3 thoughts on “Stub HttpContext

  1. Nice tip, thought I’d mention you wrote “HttpContext, HttpResponse, or HttpResponse” rather than HttpRequest I’m guessing. Feel free to delete this comment as you update the article.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s