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;

[SetUp]
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:

[Test]
private void SomeTest()
{
	helper.PrintSomeDivs(4);
	Assert.That(new Regex("<div>").Matches(responseText).Count, Is.EqualTo(4));
}
Advertisements

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

%d bloggers like this: