Skip to content Skip to sidebar Skip to footer

PHPUnit Asserting Identical HTML Structure Regardless Of Whitespace

I have a command line script that generates some HTML that I am trying to unit test using PHPUnit. Note that this HTML is not seen by a browser, so Selenium is not the right soluti

Solution 1:

Well there is DomDocument and if you want to check that the order of HTML elements matches you could use that.

If everything that differes is redundant whitespace maybe try:

$expectedDom = new DomDocument();
$expectedDom->loadHTMLFile('expected.html');
$expectedDom->preserveWhiteSpace = false;

$actualDom = new DomDocument();
$actualDom->loadHTML($this->report->generateHtml());
$actualDom->preserveWhiteSpace = false;

$this->assertEquals($expectedDom->saveHTML(), $actualDom->saveHTML());

See preservewhitespace.

What could also be worth looking into is assertEqualXMLStructure as this can be used to compare HTML as well:

assertEqualXMLStructure(
    DOMElement $expectedElement,
    DOMElement $actualElement
    [, bool $checkAttributes = false,
    string $message = '']
)

But you might run into issues with the whitespaces again so maybe you need to strip those before comparing. The benefit of using DOM is that you get much nicer error reporting in case the docs don't match.

Another way of testing XML/HTML generation is described in Practical PHPUnit: Testing XML generation.


Post a Comment for "PHPUnit Asserting Identical HTML Structure Regardless Of Whitespace"