如何使用PHPUnit对HTML输出进行单元测试?

And*_*dré 5 html phpunit unit-testing

我是PHPUnit的新手,我在单元测试HTML输出方面遇到了一些麻烦.

我的测试如下:

/**
* @covers Scrap::removeTags
*
*/
public function testRemoveTags() {

    // Variables
    $simple_parameter        = 'script';
    $array_parameter         = array('script', 'div');
    $html                    = '<div class="pubanunciomrec" style="background:#FFFFFF;"><script type="text/javascript"><!-- google_ad_slot = "9853257829"; google_ad_width = 300; google_ad_height = 250; //--></script><script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script></div><table></table>';

    // Expected HTML
    $expected_html_whitout_script     = new DOMDocument;
    $expected_html_whitout_script->loadHTML('<div class="pubanunciomrec" style="background:#FFFFFF;"></div><table></table>');
    $expected_html_without_script_div = new DOMDocument;
    $expected_html_without_script_div->loadHTML('<table></table>');

    // Actual HTML
    $actual_whitout_script     = new DOMDocument;
    $actual_whitout_script->loadHTML($this->scrap->removeTags($html, $simple_parameter));
    $actual_without_script_div = new DOMDocument;
    $actual_without_script_div->loadHTML($this->scrap->removeTags($html, $array_parameter));


    // Test
    $this->assertEquals($expected_html_whitout_script, $actual_whitout_script);
    $this->assertEquals($expected_html_without_script_div, $actual_without_script_div);

}
Run Code Online (Sandbox Code Playgroud)

我的问题是DOMDocument对象生成一些HTML代码,我无法比较它.如何打印DOMDocument对象以查看输出?有关如何比较HTML的任何线索?

对不起,我的英语不好.

最好的祝福,

Rud*_*udy 6

自2013年以来,还有另一种使用PHPUnit测试HTML输出的方法.它使用了可以在PHPUnit 3.7和3.8中找到的assertTag()方法.

例如 :

// Matcher that asserts that there is an element with an id="my_id".
$matcher = array('id' => 'my_id');

// Matcher that asserts that there is a "span" tag.
$matcher = array('tag' => 'span');

// Matcher that asserts that there is a "div", with an "ul" ancestor and a "li"
// parent (with class="enum"), and containing a "span" descendant that contains
// an element with id="my_test" and the text "Hello World".
$matcher = array(
    'tag'      => 'div',
    'ancestor' => array('tag' => 'ul'),
    'parent'   => array(
        'tag'        => 'li',
        'attributes' => array('class' => 'enum')
    ),
    'descendant' => array(
        'tag'   => 'span',
        'child' => array(
            'id'      => 'my_test',
            'content' => 'Hello World'
        )
    )
);

// Use assertTag() to apply a $matcher to a piece of $html.
$this->assertTag($matcher, $html);
Run Code Online (Sandbox Code Playgroud)

阅读官方PHPUnit网站上的更多内容.

  • `assertTag` 在 4.2 版(当前稳定版是 4.6)中被弃用,原因是突出的错误和普遍的糟糕实现(https://github.com/sebastianbergmann/phpunit/issues/1292)。该错误对话框指向一个正在进行的 PHPUnit 扩展,该扩展试图替换该功能。 (4认同)

Mic*_*uga 2

您可以使用DOMDocument 的saveHtml方法并比较输出。