Test output from HtmlTextWriter

1.8k views Asked by At

Quite simply I want to be able to test that a Asp.Net web forms server control is outputting the correct Html as it will be building dynamic content. I'm just starting to create the control and wanted to do it in a TDD style building up the Html that gets output.

I've created a separate class to do the actual Html building so that I am able to test it in isolation outside of the normal Asp.Net pipeline.

In my unit tests I can control what html is returned but I'm having problems confirming that the html contains the markup I am expecting for example:

<div id="wrapper">
    <div id="fields">
    </div>
    <div id="main">       
    </div> 
</div>

and as I'm using Nunit I would like to be able to store the output from the server control and test it by using Is.StringMatching like:

Assert.That(output, Is.StringMatching("<div id=\"main\">.*?</div>"));

This unfortunately won't work because of the extra \r \n \t instructions that the HtmlTextwriter outputs.

The way I'm currently using it is by creating a StringWriter and then using it to create the HtmlTextWriter like this:

    stringWriter = new StringWriter();
    htmlTextWriter = new HtmlTextWriter(stringWriter);

and I then call the following method:

public string Build(HtmlTextWriter writer)
{

    writer.AddAttribute(HtmlTextWriterAttribute.Id, "wrapper");
    writer.RenderBeginTag(HtmlTextWriterTag.Div);

    writer.AddAttribute(HtmlTextWriterAttribute.Id, "fields");
    writer.RenderBeginTag(HtmlTextWriterTag.Div);
    writer.RenderEndTag();
    writer.WriteLine();
    writer.AddAttribute(HtmlTextWriterAttribute.Id, "main");
    writer.RenderBeginTag(HtmlTextWriterTag.Div);
    writer.RenderEndTag();
    writer.RenderEndTag();



    return writer.InnerWriter.ToString();
}

As the Html gets more complex I can forsee additional problems verifying that the output is correct.

An additional constraint is the requirement to be able to run the tests via a CI server (most likely TeamCity) so all code or referenced libraries need to sit in my solution.

I've done a fair bit of googling but cannot seem to find much about how to test the Html output can anybody offer any suggestions for the best way forward?

3

There are 3 answers

3
Sébastien Nussbaumer On BEST ANSWER

You could make sure that your html output is well-formed xml. Then, in your testing code, load the output into an XmlDocument, thus you're free of all whitespace issues. You can then check that all the tags are really there, and are where they are supposed to be with the XmlDocument.

2
dezfowler On

I'd load it into HtmlAgilityPack and then either query that using XPath or use the fizzler project to do some QuerySelectorAll() jQuery style.

1
Yann Trevin On