Vadim's Weblog

Never stop learning.

Stub HttpContext

Posted by Vadim on March 23, 2009

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:

    [TestFixture]
    public class MyContextTester
    {
        private HttpContextBase _contextStub;
        private MyContext _myContext;

        [SetUp]
        public void StartTest()
        {
            _contextStub = MockRepository.GenerateMock<HttpContextBase>();
            _myContext = new MyContext(_contextStub);
        }

        [Test]
        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.");
        }

        [Test]
        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

About these ads

3 Responses to “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.

  2. Vadim said

    Tristan, Thanks for catching the typo.

  3. Hey thanks for this Vadim..very helpful for testing the business layer of my web applications.

    Cheers,

    Jason

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: