Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 634
Ben Aston Avatar asked Dec 14 '09 10:12

Ben Aston


2 Answers

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;
}
like image 195
Daniel Elliott Avatar answered Nov 06 '22 14:11

Daniel Elliott


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);
like image 24
C Tierney Avatar answered Nov 06 '22 16:11

C Tierney