开发者

ASP.NET MVC - Unit testing HTML that is generated by TagBuilders

I have code that generates html via TagBuilders How could I test if the right 开发者_高级运维HTML is generated? My TagBuilder is not as simple as just one tag, it also contains other tags. So I have a function that returns TagBuilder object with following HTML

<div> 
   <input type="checkbox" name=".." /> <label for=".." />
   <input type="checkbox" name=".." /> <label for=".." />
   <input type="checkbox" name=".." /> <label for=".." />
<div/>

So, to test if we have first checkbox we do:

Assert.True(MyTag.InnerHtml.Contains("<input type="checkbox" name=".." />");  

This seems wrong. Is there another way to do this?


What you can do is use HtmlAgilityPack to generate an HtmlDocument of your tag then run queries to get the number of elements etc.

HtmlDocument document = new HtmlDocument();
document.LoadHtml(MyTag.ToString());

var checkBoxCount = document.DocumentNode.DescendantNodes()
                    .Where(item => item.Name == "input" && item.GetAttributeValue("name", string.Empty) == "..")
                    .Count();

Assert.True(checkBoxCount == 3); 

You can clean up the calls by having a method that takes in a document and predicate function and returns the number of items.

With this approach, you have to be careful that the Html your methods output is valid otherwise HtmlAgilityPack will try to fix it for you, resulting in weird test issues.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜