Skip to content
September 14, 2010 / Thomas Danemar

Unit testing HtmlHelper extensions that use Response.Write in ASP.NET MVC

Unit testing HtmlHelper extensions is usually fairly straight forward. However, when the extension uses Response.Write to output text, the way to test it is less obvious. Fortunately, the solution is simple.

The trick is to mock the HttpResponse and capture the printed text in a callback. Here’s how to do it using Moq, though you can easily do using any other competent mock framework:

private HtmlHelper helper;
private string responseText;

private void Setup
	var viewContext = new Mock<ViewContext>();
	var response = new Mock<HttpResponseBase>();

	response.Setup(r => r.Write(It.IsAny<string>()))
		.Callback((string s) => responseText += s);
	viewContext.Setup(v => v.HttpContext.Response).Returns(response.Object);

	helper = new HtmlHelper(viewContext.Object, new Mock<IViewDataContainer>().Object);

You can then easily test what response text you got. Here I’m testing to make sure my extension printed the number of divs I told it to:

private void SomeTest()
	Assert.That(new Regex("<div>").Matches(responseText).Count, Is.EqualTo(4));

Leave a Reply

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

You are commenting using your 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

%d bloggers like this: