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



Tristan Smith said
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.
Vadim said
Tristan, Thanks for catching the typo.
Jason Wingfield said
Hey thanks for this Vadim..very helpful for testing the business layer of my web applications.
Cheers,
Jason