安装备忘
http://www.phpunit.de/manual/3.6/en/installation.html
对于windows下开发的人来说,先确定php的目录下有没有PEAR目录,在命令行下是否能执行 pear help指令,否则你需要执行一下Php目录下的go-pear.bat文件安装一下。
如果php版本是5.2.* 以前的独立安装包,在安装完成后应当执行一下
pear upgrade pear 更新pear-install
然后按照下面顺序执行
pear channel-discover pear.phpunit.de
pear channel-discover components.ez.no
pear channel-discover pear.symfony-project.com
pear install phpunit/PHPUnit
其实pear包是一些php脚本,你也可以下载后直接放入pear目录,但是记得下载其他的相关包
pear目录必须在include_path中
应用方法 基本
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testPushAndPop()
{
//断言 0 == 0
$this->assertEquals(0,0);
}
}
?>
大多数断言看起来很傻,事实上我们需要的也就如此,举个例子:如果用户是登录状态的,checkLogin函数返回true,否则返回false,你需要这样的断言
$this->assertEquals(checkLogin(),true,'登录状态测试失败');
doc注释@depends
/**
* @depends testEmpty
*/
public function testPush(array $stack)
depends的功能在于你可以在测试过程中保留上一个测试的状态(比如这里是testEmpty),并应用于当前测试中,其实这看起来并不一定是个好办法,因为测试间有了一定依赖关系,不便于单独维护。另外需要注意的是被depends的函数(testEmpty)不可以是下面我要介绍的 有dataProvider类型测试
@dataProvider provider
为测试提供参数,有时候你需要很多参数做同一个测试,当然你可以多写一些测试或者使用循环,不过这里有现成的方法。通过注释来指定参数提供者。数据必须是:array of arrays
<?php
class DataTest extends PHPUnit_Framework_TestCase
{
/**
* @dataProvider provider
*/
public function testAdd($a, $b, $c)
{
$this->assertEquals($c, $a + $b);
}
public function provider()
{
return array(
array(0, 0, 0),
array(0, 1, 1),
array(1, 0, 1),
array(1, 1, 3)
);
}
}
?>
有关数据提供者的信息,文档中给出大量使用spl简化操作的例子,建议多看看。
比如直接用csv文件生成参数:return new CsvFileIterator('data.csv');这里CsvFileIterator
是用户自己扩展的一个迭代器。
直接抛出失败,你可以使用trycatch来捕获异常
try{
$this->setExpectedException('InvalidArgumentException');
} catch (InvalidArgumentException $expected) {
//测试成功
return ;
}
$this->fail('An expected exception has not been raised.');
测试php错误
@expectedException PHPUnit_Framework_Error
<?php
class ExpectedErrorTest extends PHPUnit_Framework_TestCase
{
/**
* @expectedException PHPUnit_Framework_Error
*/
public function testFailingInclude()
{
include 'not_existing_file.php';
}
}
?>
对于期望输出进行测试
public function testExpectFooActualFoo()
{
$this->expectOutputString('foo');
print 'foo';
}
此外还有正则匹配,回调函数匹配方式。
在这种模式中,输出是会被捕获的,有时候我们的测试是有输出,而输出不是我们期望的,因为它可能破坏测试结果,让它看起来有点糟糕,那么用简单的法来将输出吞掉,注意红色字部分的变化,下面这个例子
<?php
class OutputTest extends PHPUnit_Extensions_OutputTestCase
{
public function testExpectFooActualFoo()
{
print '娃哈哈';
$this->assertEquals(1,1);
}
}
?>
(Please note that PHPUnit swallows all output that is emitted during the execution of a test)
比较两个xml文档的一致性的一个断言
assertXmlFileEqualsXmlFile
有时有些xml可能多了几个空格,但是结构是一致的。