Unit Testing Extension Method on HtmlHelper

I have an HTMLHelper extension method that outputs HTML in Response.Write. What is the best unit test it?

I am considering mixing up the HtmlHelper passed to a method, but I'm not sure how I should check the HTML sent to Response.Write.

thanks

+5
source share
3 answers

If you use the HTML helper to output text to the browser, why not return the string to it and, in your opinion, do something like ...

<%=Html.YourExtension() %>

This makes it much more verifiable.

Kindness,

Dan

EDIT:

Modification will be a signature change

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

to

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

html-. - , , beginform , , .

- .

:

        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);
+1

This works if the "YourExtension" method simply uses the HtmlHelper methods that return a string or HtmlString. But methods such as "BeginForm" return an MvcForm object, as well as a form tag written directly in the TextWriter referenced by HtmlHelper.

0
source

All Articles