Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 solution for this.

I'm only concerned with comparing the actual HTML structure. I'm using assertEquals() but the actual strings may not be exactly identical because of various whitespace characters.

public function testHtmlIsIdentical()
{
    $expectedReport = file_get_contents('expected.html');
    $this->report->setupSomeData('test data');
    $actualReport = $this->report->generateHtml();
    $this->assertEquals($expectedReport, $actualReport);
}

What can I do in order to compare the structure (the nodes) of the HTML instead of the strings of HTML? Is there a feature of PHPUnit that allows this? Is there a standalone library for comparing HTML?

Solution:

PHPUnit has assertions for comparing XML:

  • assertXmlFileEqualsXmlFile()
  • assertXmlStringEqualsXmlFile()
  • assertXmlStringEqualsXmlString()

The assertXmlStringEqualsXmlFile works perfectly in this scenario:

public function testHtmlIsIdentical()
{
    $this->report->setupSomeData('test data');
    $this->assertXmlStringEqualsXmlFile('expected.html', $this->report->generateHtml());
}
like image 502
Andrew Avatar asked Aug 23 '11 21:08

Andrew


1 Answers

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.

like image 177
edorian Avatar answered Nov 12 '22 09:11

edorian