在快速开发,频繁上线的项目中,代码很容易出现问题,这时候做好单元测试就非常的重要。
- 安装
项目地址:https://github.com/sebastianbergmann/phpunit/
手动安装很麻烦,推荐使用pear直接安装
yum install php-pear.noarch
pear install phpunit/PHPUnit
pear install phpunit/PHP_Invoker
pear install phpunit/PHPUnit_Selenium
pear install phpunit/PHPUnit_Story
- 使用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
| <?php
class CarTest extends CTestCase
{
public $queue;
public $fixtures=array(
'car'=>'Car',
);
/**
* 不是test开头的测试方法使用@test
*
* @test 注解么?
*/
public function noTest()
{
$this->assertEquals(1, 1);
$this->assertEquals(1, 1);
return false;
}
/**
* 依赖于noTest noTest返回值是这个参数值,noTest不过,这个检查跳过
*
* @depends noTest
*/
public function testCreate($return)
{
$this->assertFalse($return, 'failed');
}
/**
* 使用数据源验验证测试
*
* @dataProvider testProvider
*/
public function testArry($arr)
{
$this->assertArrayHasKey("return", $arr);
}
public function testProvider()
{
return array(
array(array('return' => 'ss')),
array(array('return' => 'ss')),
array(array('return' => 'ss')),
);
}
public function testException()
{
// 期待的异常
$this->setExpectedException('Exception');
// 抛出异常,测试通过
throw new Exception('test');
}
/**
* 错误异常
*
* @expectedException PHPUnit_Framework_Error
*/
public function testError()
{
// $this->fail('test');
// PHP错误会抛出框架内置的异常 PHPUnit_Framework_Error
include 'nofileffa.php';
}
public function setUp()
{
fwrite(STDOUT, 'set up');
$this->queue = array(1, 2, 3);
}
public function tearDown()
{
fwrite(STDOUT, 'tear down');
$this->queue = null;
}
public function testFixture()
{
$this->assertEquals(array(1, 2, ), $this->queue);
}
public function onNotSuccessfulTest(Exception $e)
{
fwrite(STDOUT, 'not success');
parent::onNotSuccessfulTest($e);
}
}
|
- 部分资料
断言:http://www.phpunit.de/manual/current/en/writing-tests-for-phpunit.html#writing-tests-for-phpunit.assertions
fixtures:http://www.phpunit.de/manual/current/en/fixtures.html
注解:http://www.phpunit.de/manual/current/en/appendixes.annotations.html
yii test:http://www.yiiframework.com/doc/guide/1.1/zh_cn/test.overview PHPUnit 3.7的authload换成了匿名函数,需要改一下,不然yii加载会有问题.