`
shangjava
  • 浏览: 1190121 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

PHPUnit袖珍指南-第二章 自动测试

阅读更多

第二章 自动测试

最好的程序员也会犯错误。好程序员和差程序员的区别在于:好程序员能通过测试尽可能的发现错误。你越快测试错误,你就越快发现它们,发现和修正的成本就越低。这解释了为什么只在软件发布前才测试的做法为什么问题那么多。大多数错误根本就没有发现过,修正发现的错误是那么的高,以至于你不得不根据优先级来决定只修正那些错误,因为你根本就承受不起全部修正的费用。

相比你正在使用的方法,采用PHPUnit进行测试并不是一个全然不同的东西。它们只是方法不同。两者之间的不同在于,检查程序行为是否符合正确是通过一批可以自动测试的代码片断来进行的。这些代码片断叫做单元测试。

在这一部分,我们先基于打印的测试代码进行自动测试。假设我们要测试PHP的内建数组Array。需要测试之一是函数sizeof(),对任何新创建的数组,sizeof()函数应该返回 0。当我们加入一个新数组成员,sizeof()应该返回1。例1显示了我们想测试什么。

1. 测试数组和sizeof()

<?php

$fixture = Array( );

// $fixture应该为空。

$fixture[] = "element";

// $fixture应该包含一个数组成员。

?>

最简单的测试方法是在加入数组成员前后打印sizeof()的运算结果,如果返回01,说明Arraysizeof()运行正常。

2. 采用打印语句测试Arraysizeof()

<?php

$fixture = Array( );

print sizeof($fixture) . "\n";

$fixture[] = "element";

print sizeof($fixture) . "\n";

?>

0

1

现在,我们让测试程序从需要手工解释变为自动运行。在例3中,我们比较了期望值和实际值,如果相等就打印ok。如果我们发现有的结果不是ok,我们就知道有问题了。

3. 比较Arraysizeof()的期望值和实际值

<?php

$fixture = Array( );

print sizeof($fixture) == 0 ? "ok\n" : "not ok\n";

$fixture[] = "element";

print sizeof($fixture) == 1 ? "ok\n" : "not ok\n";

?>

ok

ok

我们现在引入一个新的要素,如果期望值和实际值不同,我们就抛出一个异常。这样我们的输出就更简单了。如果测试成功,什么也不做,如果有一个未处理异常,我们知道有问题了。

4.使用断言函数来测试Arraysizeof()

<?php

$fixture = Array( );

assertTrue(sizeof($fixture) = = 0);

$fixture[] = "element";

assertTrue(sizeof($fixture) = = 1);

function assertTrue($condition) {

 if (!$condition) {

 throw new Exception("Assertion failed.");

 }

}

?>

现在测试完全自动化了。和我们第一个版本不同,这个版本使得测试完全自动化了。

使用自动测试的目的是尽可能少的犯错误。尽管你的代码还不是完美的,用优良的自动测试,你会发现错误会明显减少。自动测试给了你对代码公正的信心。有这个信心,你可以在设计上有大胆的飞越(参见本书后“重构”一章),和你的团队伙伴关系更好(参见本书后“跨团队测试”一章),改善你和客户之间的关系,每天安心入睡,因为你可以证明由于你的努力,系统变得更好了。

--------------------------------------------------------------------------------------------------------------------

原文:

Chapter 2. Automating Tests

Even good programmers make mistakes. The difference between a good programmer and a bad programmer is that the good programmer uses tests to detect his mistakes as soon as possible. The sooner you test for a mistake, the greater your chance of finding it, and the less it will cost to find and fix. This explains why it is so problematic to leave testing until just before releasing software. Most errors do not get caught at all, and the cost of fixing the ones you do catch is so high that you have to perform triage with the errors because you just cannot afford to fix them all.

Testing with PHPUnit is not a totally different activity from what you should already be doing. It is just a different way of doing it. The difference is between testingthat is, checking that your program behaves as expectedand performing a battery of testsrunnable code-fragments that automatically test the correctness of parts (units) of the software. These runnable code-fragments are called unit tests.

In this section, we will go from simple print-based testing code to a fully automated test. Imagine that we have been asked to test PHP's built-in Array. One bit of functionality to test is the function sizeof( ). For a newly created array, we expect the sizeof( ) function to return 0. After we add an element, sizeof( ) should return 1. Example 1 shows what we want to test.

Example 1. Testing Array and sizeof( )

<?php

$fixture = Array( );

// $fixture is expected to be empty.

$fixture[] = "element";

// $fixture is expected to contain one element.

?>

A really simple way to check whether we are getting the results we expect is to print the result of sizeof( ) before and after adding the element (see Example 2). If we get 0 and then 1, Array and sizeof( ) are behaving as expected.

Example 2. Using print to test Array and sizeof( )

<?php

$fixture = Array( );

print sizeof($fixture) . "\n";

$fixture[] = "element";

print sizeof($fixture) . "\n";

?>

0

1

Now, we would like to move from tests that require manual interpretation to tests that can run automatically. In Example 3, we write the comparison of the expected and actual values into the test code and print ok if the values are equal. If we see a not ok message, we know something is wrong.

Example 3. Comparing expected and actual values to test Array and sizeof( )

<?php

$fixture = Array( );

print sizeof($fixture) == 0 ? "ok\n" : "not ok\n";

$fixture[] = "element";

print sizeof($fixture) == 1 ? "ok\n" : "not ok\n";

?>

ok

ok

We now factor out the comparison of expected and actual values into a function that raises an exception when there is a discrepancy (Example 4). Now our test output gets simpler. Nothing gets printed if the test succeeds. If we see an unhandled exception, we know something has gone wrong.

Example 4. Using an assertion function to test Array and sizeof( )

<?php

$fixture = Array( );

assertTrue(sizeof($fixture) = = 0);

$fixture[] = "element";

assertTrue(sizeof($fixture) = = 1);

function assertTrue($condition) {

if (!$condition) {

throw new Exception("Assertion failed.");

}

}

?>

The test is now completely automated. Instead of just testing as we did with our first version, with this version, we have an automated test.

The goal of using automated tests is to make fewer mistakes. While your code will still not be perfect, even with excellent tests, you will likely see a dramatic reduction in defects once you start automating tests. Automated tests give you justified confidence in your code. You can use this confidence to take more daring leaps in design (see "Refactoring," later in this book), get along better with your teammates (see "CrossTeam Tests," later in this book), improve relations with your customers, and go home every night with proof that the system is better now than it was that morning because of your efforts.

分享到:
评论

相关推荐

    PHPUnit袖珍指南.doc

    PHPUnit袖珍指南.doc PHPUnit 单元测试 从环境配置到 段元详细介绍

    phpunit-clever-and-smart, 更智能的runner 测试.zip

    phpunit-clever-and-smart, 更智能的runner 测试 PHPUnit的智能测试 runner 任务通过在数据库中存储测试用例并按以下顺序在连续运行中重新排序测试来启用快速反馈周期:失败和错误迄今为止未记录的测试按执行时间( ...

    phpunit-mock-objects, PHPUnit的模拟对象库.zip

    phpunit-mock-objects, PHPUnit的模拟对象库 PHPUnit_MockObjectPHPUnit_MockObject 是PHPUnit默认的模拟对象库。要求PHP 5.6是必需的,但使用最新版本的PHP非常安装你可以使用 Composer 将这里库作为

    PHPUnit袖珍指南之自动测试

    相比你正在使用的方法,采用PHPUnit进行测试并不是一个全然不同的东西。它们只是方法不同。两者之间的不同在于,检查程序行为是否符合正确是通过一批可以自动测试的代码片断来进行的。这些代码片断叫做单元测试。 在...

    PHPUnit中文手册-PDF-5.1

    网上找到的文档都是比较老旧的了,在官网上找到了最新版的中文手册,觉得还不错,分享给大家。 附上来源地址:https://phpunit.de/documentation.html PHPUnit中文站:...PHPUnit官方站:https://phpunit.de/

    PHPUnit PDF手册【袖珍指南】

    PHPunit pdf教程,非常不错,值得推荐

    Laravel开发-phpunit-selenium-webdriver

    Laravel开发-phpunit-selenium-webdriver WebDriver支持使用Fluent测试API的phpunit Selenium测试用例。

    PHPUnit袖珍指南之装置器

    编写测试最耗时的部分是边编写设置整个程序到达一个已知状态,而后在测试结束后返回到原始状态。这个已知状态叫做测试的装置器。本文将为大家介绍PHPUnit袖珍指南之装置器。

    phpunit-pretty-result-printer:PHPUnit漂亮结果打印机-使您PHPUnit测试看起来漂亮!

    如果要从以前的版本升级,并且已在本地发布phpunit-printer.yml ,请确保将以下内容添加到选项部分 ... cd-printer-dont-format-classname : false ... 执行初始化脚本(可选) 以下步骤是可选的,但将为实现...

    Etsy的PHPUnit扩展phpunit-extensions.zip

    phpunit-extensions 是 Etsy 的 PHPUnit 扩展。 标签:phpunit

    phpunit-coverage-check:检查phpunit代码覆盖率的工具

    PHPUnit覆盖率检查工具安装composer require --dev iro88/phpunit-coverage-check用法示例根据文本输出检查 # using streamset -o pipefail && phpunit | phpunit-coverage-check --format=text 85.00# ...with ...

    PHPUnit袖珍指南之PHPUnit的目的

    当我们开始测试大量的array_*()函数时,每个都需要一个测试。我们可以每 个都从头写起。但是,更好的方法是一次性写好一个测试基础构架,以后就只用写每个测试不同的部分。PHPUnit就是这样一个基础构架。

    phpunit-speedtrap, 在PHPUnit测试套件中,报告缓慢运行的测试.zip

    phpunit-speedtrap, 在PHPUnit测试套件中,报告缓慢运行的测试 phpunit-speedtrap SpeedTrap报告你的控制台中PHPUnit测试套件中运行缓慢的测试。影响测试执行时间的许多因素。 测试没有正确地从变量延迟( 数据库,...

    phpunit-github-actions-printer

    phpunit-github-actions-printer 在有一种零配置方式来实现这一这是一台PHPUnit打印机,使用GitHub Actions的::error和::warning功能为失败的测试运行添加注释。 与上述内容的主要区别在于,它支持添加除错误之外的...

    phpunit-json-assertions:PHPUnit的JSON断言(包括JSON模式)

    phpunit-json-assertions PHPUnit的JSON断言包含特征/方法,以帮助通过各种方法验证JSON数据。 特征 通过JSON模式验证JSON数据 描述您现有的数据格式 清晰的,人为和机器可读的文档 完整的结构验证,对 自动化测试 ...

    phpunit-code-quality:一旦PHPUnit测试通过,请检查代码质量

    composer require --dev drawmyattention/phpunit-code-quality 将测试监听器注册到您的phpunit.xml文件: &lt; object class = " DrawMyAttention\CodeQuality\ComplexityAnalyser " /&gt; &lt; bool&gt;true ...

    ci-phpunit-test, 一种简单的使用 PHPUnit 3.x 语言的方法.zip

    ci-phpunit-test, 一种简单的使用 PHPUnit 3.x 语言的方法 ci-phpunit-test用于 CodeIgniter 3 。x 在 CodeIgniter 3. x. 中使用PHPUnit的简便方法你根本不需要修改CodeIgniter核心文件。你可以轻松编

    针对phpunit 接口自动化测试系列

    针对接口自动化----phpunit 接口自动化测试系列,接口自动化用例的编写以及PHP及PHPUNIT的安装

    phpunit-pretty-print::white_heavy_check_mark:使您PHPUnit输出漂亮

    phpunit-pretty-print :white_heavy_check_mark: 使您PHPUnit输出漂亮 安装 composer require sempro/phpunit-pretty-print --dev 该软件包需要&gt;=7.0.0PHPUnit。 如果您在6.x运行,请使用1.0.3版。 如果您在9.x...

    phpunit-parallel:PHPUnit并发测试执行器

    放弃-phpunit-parallel 另一个PHPUnit并发测试执行器 我不再维护该项目,它仅在这里作为存档。 另一种方法是,检查出 它是如何工作的? phpunit-parallel使用基于react-php的even循环与许多辅助进程进行通信。 它...

Global site tag (gtag.js) - Google Analytics