phpunit 单元测试

PHPUnit依赖测试详解

1、ubuntu12.04安装

1
2
3
wget https://phar.phpunit.de/phpunit.phar
chmod +x phpunit.phar
mv phpunit.phar /usr/local/bin/phpunit

2、测试案例phpunit1.php(测试的依赖关系)

展示如何用@depends标注来表达测试方法之间的依赖关系

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
<?php
class StackTest extends PHPUnit_Framework_TestCase
{
public function testEmpty()
{
$stack array();
$this->assertEmpty($stack);
 
return $stack;
}
 
/**
* @depends testEmpty
*/
public function testPush(array $stack)
{
array_push($stack'foo');
$this->assertEquals('foo'$stack[count($stack)-1]);
$this->assertNotEmpty($stack);
 
return $stack;
}
 
/**
* @depends testPush
*/
public function testPop(array $stack)
{
$this->assertEquals('foo'array_pop($stack));
$this->assertEmpty($stack);
}
}

3、测试结果

1
2
3
4
5
phpunit phpunit1.php
PHPUnit 3.7.27 by Sebastian Bergmann.
...
Time: 4 ms, Memory: 4.25Mb
OK (3 tests, 5 assertions)

4、为了快速定位缺陷,我们希望把注意力集中于相关的失败测试上。这就是为什么当某个测试所依赖的测试失败时,PHPUnit会跳过这个测试。通过利用测试之间的依赖关系,缺陷定位得到了改进。

如下案例phpunit2.php:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
class DependencyFailureTest extends PHPUnit_Framework_TestCase
{
public function testOne()
{
$this->assertTrue(FALSE);
}
 
/**
* @depends testOne
*/
public function testTwo()
{
}
}
?>

5、执行结果

1
2
3
4
5
6
7
8
9
10
phpunit phpunit2.php
PHPUnit 3.7.27 by Sebastian Bergmann.
FS
Time: 2 ms, Memory: 4.00Mb
There was 1 failure:
1) DependencyFailureTest::testOne
Failed asserting that false is true.
/home/wwwroot/local.guazi.com/webroot/phpunit2.php:6
FAILURES!
Tests: 1, Assertions: 1, Failures: 1, Skipped: 1.

6、测试可以使用多于一个@depends标注。PHPUnit不会更改测试的运行顺序,因此你需要自行保证某个测试所依赖的所有测试均出现于这个测试之前。

拥有多个@depends标注的测试,其第一个参数是第一个生产者提供的基境,第二个参数是第二个生产者提供的基境,以此类推

案例phpunit3.php

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
<?php
class MultipleDependenciesTest extends PHPUnit_Framework_TestCase
{
public function testProducerFirst()
{
$this->assertTrue(true);
return 'first';
}
 
public function testProducerSecond()
{
$this->assertTrue(true);
return 'second';
}
 
/**
* @depends testProducerFirst
* @depends testProducerSecond
*/
public function testConsumer()
{
$this->assertEquals(
array('first''second'),
func_get_args()
);
}
}
?>

7、执行结果

1
2
3
4
5
phpunit phpunit3.php
PHPUnit 3.7.27 by Sebastian Bergmann.
...
Time: 4 ms, Memory: 4.25Mb
OK (3 tests, 3 assertions)






















本文转自shayang8851CTO博客,原文链接:http://blog.51cto.com/janephp/1298842,如需转载请自行联系原作者
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值