php - 在 PHPUnit 中为页面上的 XML 元素测试断言?

标签 php testing phpunit

我想断言 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
        );
    }
}

关于php - 在 PHPUnit 中为页面上的 XML 元素测试断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31363239/

相关文章:

javascript - 我如何 Jest 测试带有 promise 的服务调用

symfony - 在 SF3.4 及更高版本中运行 Symfony DIC 烟雾测试

php - 为什么我无法向 MySQL 插入数据?

php - 是否有必要使用 mysql_real_escape_string() 将图像导入 mysql?

testing - Web 应用程序测试框架的组织和结构

java - 如何使用 clojure 单元测试获得 java 生产代码的代码覆盖率?

php - 在 PHPUnit 中模拟具有内部依赖关系的对象

使用 PHP7.2 和 7.1 运行的 phpunit 测试比使用 PHP7.0 运行时慢 3 倍

PHP 5.3.0 USE 关键字——如何在 5.2 中向后移植?

PHP AMQP Consume() fork 做实际工作