2015-07-12 42 views
1

我想斷言PHP中頁面上的XML元素中的元素被聲明爲相等。在PHPUnit中測試頁面上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> 

回答

1

如果你需要知道的是正確的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 
     ); 
    } 
}