Sunday, 2 August 2009

Unit Testing - HttpSimulator

Have you ever wondered how to simulate HttpContext so that you can write your unit tests? TypeMock can do that but it's not a free tool.

HttpSimulator is a component composed of 2 classes; I am not sure whether Phil Haak has written it himself but it solves that problem nicely. You can download it from the bottom of this post.

Code sample:

public static HttpSimulator CreateHttpSimulator()
return new HttpSimulator("/", @"c:\inetpub\").SimulateRequest();

public void SetSessionTest()
using (Helper.CreateHttpSimulator())
// setup
var expectedValue = 2;
// exercise
Utils.SetSession(SessionKey.Basket, expectedValue);
// verify
var actualValue = Utils.GetFromSession(SessionKey.Basket);
Assert.AreEqual(expectedValue, actualValue);
System Under Test:

public static void SetSession(SessionKey key, object value)
HttpContext.Current.Session[key.ToString()] = value;

public static object GetFromSession(SessionKey key)
if (HttpContext.Current == null HttpContext.Current.Session == null)
throw new ApplicationException("HttpContext.Current.Session is null");

if (HttpContext.Current.Session[key.ToString()] == null)
return null;

return HttpContext.Current.Session[key.ToString()];

1 comment:

Gil Zilberfeld said...

Hi Pooya,

First - thanks for mentioning Typemock Isolator.

I'm assuming you're using this a lot in your app. Is this enough, or do you need to wrap more objects as well?


Gil Zilberfeld