Unit testing Controller.Initialize()

We recently had a case where we wanted to unit test some logic in the Controller.Initialize() method. This method is executed fairly early in the controller’s lifespan, and runs before the action is executed. It itself is a protected method, and is itself called by Controller.Execute.

Firstly, I needed to mock an HttpContext out:

private static HttpContext MockHttpContext
{
	get
	{
		var httpRequest = new HttpRequest("", "http://beingabstract/", "");
		var stringWriter = new StringWriter();
		var httpResponce = new HttpResponse(stringWriter);
		var httpContext = new HttpContext(httpRequest, httpResponce);
 
		return httpContext;
	}
}

I then needed to prepare a RequestContext instance:

var wrapper = new HttpContextWrapper(MockHttpContext);
var routeData = new RouteData();
routeData.Values.Add("productKey", "test");

Finally, I created a stub in my test project to allow me to get at the function. The advantage of doing it this way is that I don’t need to stub out any more then I need to. Ordinarily I would need to get enough working stubs to pass through the rest of the Execute process, but by simply setting up a test wrapper I can expose only the method that I need to:

internal class ExampleControllerWrapper : ExampleController
{
	public void TestInitialise(RequestContext context)
	{
		this.Initialize(context);
	}
}

Leave a Reply

Your email address will not be published. Required fields are marked *