在PHPUnit中测试页面上XML元素的断言


Test assertions in PHPUnit for XML elements on a page?

我想断言PHP页面上XML元素中的元素是相等的。

做两个测试的最好方法是什么?一个在第一个ip上,一个在第二个ip标签上?

把脚趾浸入水中:

public function testPPTPRangeChecker(){
echo "Loggin in as the adinistrator";
//Login as the administrator
$client = $this->myLoginAs('adminuser','Testing1!');
echo "The test user has successfully logged in as administrator";
$crawler = $client->request('POST', '/config/19/46');
echo "The site has navigated successfully to the config page";
    $this->assertTag(
        array(
            'tag' => 'ip',
            'content' => '192.168.1.1'
            )
        );
<标题> XML
<pptpd>
        <user>
            <name>testuser</name>
            <ip>192.168.1.1</ip>
            <password>testpass</password>
        </user>
        <user>
            <name>testuser2</name>
            <ip>192.168.1.2</ip>
            <password>testpass2</password>
        </user>
    </pptpd>

如果您只需要知道是否存在正确的IP,则可以使用xpath。如果你需要确保整个XML结构是正确的,你可以使用assertEqualXMLStructure。

class MyTest extends 'PHPUnit_Framework_TestCase
{
    private $expectedXML = <<<EOF
<pptpd>
        <user>
            <name>testuser</name>
            <ip>192.168.1.1</ip>
            <password>testpass</password>
        </user>
        <user>
            <name>testuser2</name>
            <ip>192.168.1.2</ip>
            <password>testpass2</password>
        </user>
    </pptpd>
EOF;
    public function testMy1()
    {
        $actualXml = $this->expectedXML;
        $doc = new 'DomDocument();
        $doc->loadXML($actualXml);
        $xpath = new 'DOMXPath($doc);
        $this->assertSame(1, $xpath->query('//pptpd/user[ip="192.168.1.1"]')->length);
    }
    public function testMy2()
    {
        $actualXml = $this->expectedXML;
        $expected = new 'DOMDocument();
        $expected->loadXML($this->expectedXML);
        $actual = new 'DOMDocument();
        $actual->loadXML($actualXml);
        $this->assertEqualXMLStructure(
            $expected->firstChild->childNodes->item(1),
            $actual->firstChild->childNodes->item(1),
            true
        );
    }
}