设为首页 收藏本站
查看: 905|回复: 0

[经验分享] [PHP]用PHPUnit进行测试驱动开发(Test-Driven Development)

[复制链接]

尚未签到

发表于 2015-8-28 07:59:28 | 显示全部楼层 |阅读模式
单元测试是软件开发过程中极其重要的一部分,几个著名的软件开发实践都推崇以单元测试为主导:
Test-First Programming, Extreme Programming(XP极限编程), Test-Driven Development(TDD,敏捷方法的核心实践).
它们也允许那些即使在语言结构上并不支持这种方法论的编程语言使用Design-by-Contract(契约式设计)。
你可以在你开发的过程中用PHPUnit写test。然而,在新错误发生时越快写好test越有价值,所以在代码完成后几个月才去写test,不如在一个defect发生后
马上写。既然如此,为什么不干脆在defect可能引入前写呢?(Test-First Programming)
Test-First Programming是XP和TDD的一部分,它就是基于这种思路并且将其发挥至极致。依靠今日计算机的强大性能,我们可以每天RUN成千上万个test。
我们可以从这些测试中获取的反馈来保证代码的每一小步的质量。这些test就像pitons(岩钉),确保不管发生了什么,你只能落到上一步结束的位置。
当你先写test,它可能无法运行,因为它要调用的对象和方法还没有coding。一开始可能觉得奇怪,但你马上就能适应它。如果你遵循面向对象原则使用
接口编程,Test-First Programming是最实用的实践。当你写test的时候,你在思考你所要测试对象的接口,这是从外部去观察这个对象。当你要让这个test
真正跑起来,你在进行纯抽象的思考。这样,接口的错误就可以被失败的test修复。
The point of Test-Driven Development is to drive out the functionality the software actually needs, rather than what the programmer thinks it probably ought to have. The way it does this seems at first counterintuitive, if not downright silly, but it not only makes sense, it also quickly becomes a natural and elegant way to develop software.
--Dan North
TDD的要点是drive out软件确切需要的功能,而不是程序员自己认为应该实现的功能。这初看起来是违反直觉的,其实它不光是合理的,而且快速成为软件开发一种自然而优雅的方式。
--Dan North
接下来用一个例子简要介绍如何进行TDD。要想更详细的了解,推荐几本书:
Test-Driven Development [Beck2002]  by Kent Beck;
A Practical Guide to Test-Driven Development [Astels2003] by Dave Astels;

银行账户例子
BankAccount类需要deposit(存款)和withdraw(取现)方法。而且它要遵守下面2个契约条件:
1、银行账户初始值必须为0.
2、银行账户值不能为负。
在编码实现这个类之前我们先写test,我们用契约条件作为设计test的准则

DSC0000.gif DSC0001.gif 代码

1 DSC0002.gif <?php
2require_once 'PHPUnit/Framework.php';
3require_once 'BankAccount.php';
4
5class BankAccountTest extends PHPUnit_Framework_TestCase
6{
7    protected $ba;
8
9    protected function setUp()
10    {
11        $this->ba = new BankAccount;
12    }
13
14    public function testBalanceIsInitiallyZero()
15    {
16        $this->assertEquals(0, $this->ba->getBalance());
17    }
18
19    public function testBalanceCannotBecomeNegative()
20    {
21        try {
22            $this->ba->withdrawMoney(1);
23        }
24
25        catch (BankAccountException $e) {
26            $this->assertEquals(0, $this->ba->getBalance());
27
28            return;
29        }
30
31        $this->fail();
32    }
33
34    public function testBalanceCannotBecomeNegative2()
35    {
36        try {
37            $this->ba->depositMoney(-1);
38        }
39
40        catch (BankAccountException $e) {
41            $this->assertEquals(0, $this->ba->getBalance());
42
43            return;
44        }
45
46        $this->fail();
47    }
48}
49?>
接下来我们开始写BankAccount类,我们为了让第一个test,testBalanceIsInitiallyZero()能够成功跑起来,我们写最少的代码。

代码

1<?php
2class BankAccount
3{
4    protected $balance = 0;
5
6    public function getBalance()
7    {
8        return $this->balance;
9    }
10}
11?>
phpunit BankAccountTest
PHPUnit 3.4.2 by Sebastian Bergmann.
.
  Fatal error: Call to undefined method BankAccount::withdrawMoney()
  
这样第一个test就能通过了,第二个现在还无法pass,接下来继续完善BankAccount类

代码

1<?php
2class BankAccount
3{
4    protected $balance = 0;
5
6    public function getBalance()
7    {
8        return $this->balance;
9    }
10
11    protected function setBalance($balance)
12    {
13        if ($balance >= 0) {
14            $this->balance = $balance;
15        } else {
16            throw new BankAccountException;
17        }
18    }
19
20    public function depositMoney($balance)
21    {
22        $this->setBalance($this->getBalance() + $balance);
23
24        return $this->getBalance();
25    }
26
27    public function withdrawMoney($balance)
28    {
29        $this->setBalance($this->getBalance() - $balance);
30
31        return $this->getBalance();
32    }
33}
34?>
phpunit BankAccountTest
PHPUnit 3.4.2 by Sebastian Bergmann.
...
Time: 0 seconds

OK (3 tests, 3 assertions)
除了上面这样写,你也可以使用PHPUnit_Framework_Assert类提供的静态assertion方法来把条件按契约式风格写进你的代码,
如果其中一个失败,一个PHPUnit_Framework_AssertionFailedError异常会抛出。这种方式你为条件检查所写的代码更少,而且测试代码
可读性也更好。但是,你使得PHPUnit的环境依赖加入了你的项目。
Design-by-Contract assertions

代码

1<?php
2require_once 'PHPUnit/Framework.php';
3
4class BankAccount
5{
6    private $balance = 0;
7
8    public function getBalance()
9    {
10        return $this->balance;
11    }
12
13    protected function setBalance($balance)
14    {
15        PHPUnit_Framework_Assert::assertTrue($balance >= 0);
16
17        $this->balance = $balance;
18    }
19
20    public function depositMoney($amount)
21    {
22        PHPUnit_Framework_Assert::assertTrue($amount >= 0);
23
24        $this->setBalance($this->getBalance() + $amount);
25
26        return $this->getBalance();
27    }
28
29    public function withdrawMoney($amount)
30    {
31        PHPUnit_Framework_Assert::assertTrue($amount >= 0);
32        PHPUnit_Framework_Assert::assertTrue($this->balance >= $amount);
33
34        $this->setBalance($this->getBalance() - $amount);
35
36        return $this->getBalance();
37    }
38}
39?>
这样我们使用了契约式设计来开发BankAccount类。写的时候注意遵循Test-First Programming,代码必须让测试通过。然而我们忘记
去写用来测试setBalance()、depositMoney()、withdrawMoney()符合契约条件时的test了。我们需要一种机制来测试我们的test或者至少
来衡量它们的质量。这就是接下来将讨论的代码覆盖率分析(analysis of code-coverage information).

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-105194-1-1.html 上篇帖子: [php]php设计模式 Observer(观察者模式) 下篇帖子: each与list的用法(PHP学习)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表