Validate HTML using Fluent Assertions

ASP.NET HTML helpers often return dynamically built HTML that may or may not be valid.

In this case, it makes sense to test the validity of the returned value as part of the automated tests. As I’m a big fan of Fluent Assertions and use them for all my assertions, I created a simple extension to validate the HTML using HtmlAgilityPack.

Assertion Class

public class HtmlStringAssertions : ReferenceTypeAssertions<HtmlString, HtmlStringAssertions> {

    public HtmlStringAssertions(HtmlString instance) {
        Subject = instance;
    }

    protected override string Identifier => "HtmlString";

    public AndConstraint<HtmlStringAssertions> BeValidHtml(string because = "", params object[] becauseArgs) {
        Execute.Assertion
            .BecauseOf(because, becauseArgs)
            .Given(() => {
                var htmlDocument = new HtmlDocument();
                htmlDocument.LoadHtml(Subject.ToString());

                return htmlDocument;
            })
            .ForCondition(htmlDocument => !htmlDocument.ParseErrors.Any())
            .FailWith("Expected {context:HtmlString} to contain valid HTML{reason}.");

        return new AndConstraint<HtmlStringAssertions>(this);
    }

}

Extension Method

public static class HtmlStringExtensions  {

    public static HtmlStringAssertions Should(this HtmlString instance) {
        return new HtmlStringAssertions(instance);
    }

}

Usage

// ...
var htmlString = myHelper.CreateSomeMarkup(param1, param2);

htmlString.Should().BeValidHtml();