开发者

Unit Testing An Extension Method on HtmlHelper

开发者 https://www.devze.com 2022-12-14 10:36 出处:网络
I have an HTMLHelper extension method that outputs HTML to Response.Write. How best to unit test this?

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

I'm considering mocking the HtmlHelper pa开发者_StackOverflow中文版ssed into the method, but am unsure as to how I should verify the HTML sent to Response.Write.

Thanks


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;
}


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消