如何编写更优雅的Unit-Test以断言某些浏览器的ie.css文件已被添加到条件注释之间的head部分:
html源代码:
<!DOCTYPE html>
<html>
<head>
<title></title>
<link href="/css/blueprint/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />
<!--[if lt IE 8]> <link href="/css/blueprint/ie.css" media="screen, projection" rel="stylesheet" type="text/css" /><![endif]-->
我的测试类来自Zend_Test_PHPUnit_ControllerTestCase
:
<?php
class BlueprintTest extends Zend_Test_PHPUnit_ControllerTestCase
{
public function setUp()
{
$this->bootstrap = new Zend_Application(APPLICATION_ENV,
APPLICATION_PATH . '/configs/application.ini');
parent::setUp();
}
此尝试失败,类似的测试声明screen.css
文件位于主题部分:
/**
* this test FAILS
*/
public function testBlueprintMSIEScreenCssIncluded()
{
$this->dispatch('/');
$xpath = '/html/head/link'
. '[@rel="stylesheet"]'
. '[@href="/css/blueprint/ie.css"]'
. '[@type="text/css"]'
. '[@media="screen, projection"]';
$this->assertXpathCount($xpath, 1);
}
最后我写了一个测试通过,但它是如此“不美观”,我真的想学习如何以更好的方式做到这一点:
/**
* this test passes, but i do not like the way it is done:
*/
public function testBlueprintMSIECssIncludedUsingUglyLongGeneratedRegex()
{
$this->dispatch('/');
$p = array(
'rel\s*=\s*"stylesheet"',
'href\s*=\s*"/css/blueprint/ie\.css"',
'type\s*=\s*"text/css"',
'media\s*=\s*"screen, projection"'
);
$tmp = array();
foreach($p as $a) {
foreach($p as $b) {
if($b == $a) continue;
foreach($p as $c) {
if($c == $a || $c == $b) continue;
foreach($p as $d) {
if($d == $a || $d == $b || $d == $c) continue;
$tmp[] = "($a\s+$b\s+$c\s+$d)";
}
}
}
}
$pattern = '#<!--\[if lt IE 8\]>[\s\n]*'
. '<link\s+' . implode("|", $tmp) . '\s*[/]*>[\s\n]*'
. '<!\[endif\]-->#im';
$this->assertQueryContentRegex('html head', $pattern);
}
我怎样才能做得更好? 提前谢谢!