Ben Aston
Ben Aston

Reputation: 55779

Unit Testing An Extension Method on HtmlHelper

I have an HTMLHelper extension method that outputs HTML to Response.Write. How best to unit test this?

I'm considering mocking the HtmlHelper passed into the method, but am unsure as to how I should verify the HTML sent to Response.Write.

Thanks

Upvotes: 6

Views: 1611

Answers (3)

C Tierney
C Tierney

Reputation: 1121

I use the following code to test and validate html helpers. If you are doing anything complex, like disposable based helpers like beginform or helpers with dependencies you need a better test framework then just looking at the string of a single helper.

Validation is a another example.

Try the following:

        var sb = new StringBuilder();
        var context = new ViewContext();
        context.ViewData = new ViewDataDictionary(_testModel);
        context.Writer = new StringWriter(sb);
        var page = new ViewPage<TestModel>();
        var helper = new HtmlHelper<TestModel>(context, page);

        //Do your stuff here to exercise your helper


        //Get the results of all helpers
        var result = sb.ToString();

        //Asserts and string tests here for emitted HTML
        Assert.IsNotNullOrEmpty(result);

Upvotes: 1

Charasala
Charasala

Reputation: 181

This works if the method "YourExtension" is simply using HtmlHelper methods that return string or HtmlString. But methods like "BeginForm" return MvcForm object and also the form tag is written directly on TextWriter that HtmlHelper has reference to.

Upvotes: 0

Daniel Elliott
Daniel Elliott

Reputation: 22887

If you are using an HTML helper to output text to the browser why not have it return a string and in your view do something like ...

<%=Html.YourExtension() %>

It makes it a great deal more testable.

Kindness,

Dan

EDIT:

Modification would be a change of signature

public static void YourExtension(this HtmlHelper html)
{
   ...
   Response.Write(outputSting);
}

to

public static string YourExtension(this HtmlHelper html)
{
   ...
   return outputSting;
}

Upvotes: 5

Related Questions