我正在测试一个生成PHP值的HTML表示的方法。测试方法如下所示:
public function testIndexedArray()
{
$array = array('alpha','beta','gamma');
$element_dom = method_that_turns_array_into_DOMDocument();
$xpath = new \DOMXPath($element_dom);
$this->assertEquals(1, $xpath->query("/div/em[text()='array']")->length);
$this->assertEquals(1, $xpath->query("/div/ul")->length);
$this->assertEquals(count($array), $xpath->query("/div/ul/li")->length);
$nodes = $xpath->query("/div/ul/li");
foreach ($array as $index => $value) {
$node = $nodes->item($index);
$this->assertEquals(1, $xpath->query("/li/strong[text()='$index']", $node)->length);
$this->assertEquals(1, $xpath->query("/li/em[text()='string']", $node)->length);
$this->assertEquals(1, $xpath->query("/li/span[text()=concat(\"'\",'$value',\"'\")]", $node)->length);
}
}
$element_dom->saveHTML()
生成的HTML就是这样(格式化为可读性):
<div>
<em>array</em>
<ul>
<li><strong>0</strong> <em>string</em> <span>'alpha'</span></li>
<li><strong>1</strong> <em>string</em> <span>'beta'</span></li>
<li><strong>2</strong> <em>string</em> <span>'gamma'</span></li>
</ul>
</div>
这是我期待的HTML。但是我的测试在foreach($array)
循环中的第一个断言失败了。我最难调整查询以使此测试通过。如何解决这些问题?
答案 0 :(得分:2)
循环中的查询有两个问题:
li
,因此您不应该使用它开始查询/
(check an example from manual)具有固定查询的行(使用PHP 7.2检查):
$this->assertEquals(1, $xpath->query("strong[text()='$index']", $node)->length);
$this->assertEquals(1, $xpath->query("em[text()='string']", $node)->length);
$this->assertEquals(1, $xpath->query("span[text()=concat(\"'\",'$value',\"'\")]", $node)->length);