第二章 自动测试
最好的程序员也会犯错误。好程序员和差程序员的区别在于:好程序员能通过测试尽可能的发现错误。你越快测试错误,你就越快发现它们,发现和修正的成本就越低。这解释了为什么只在软件发布前才测试的做法为什么问题那么多。大多数错误根本就没有发现过,修正发现的错误是那么的高,以至于你不得不根据优先级来决定只修正那些错误,因为你根本就承受不起全部修正的费用。
相比你正在使用的方法,采用PHPUnit进行测试并不是一个全然不同的东西。它们只是方法不同。两者之间的不同在于,检查程序行为是否符合正确是通过一批可以自动测试的代码片断来进行的。这些代码片断叫做单元测试。
在这一部分,我们先基于打印的测试代码进行自动测试。假设我们要测试PHP的内建数组Array。需要测试之一是函数sizeof(),对任何新创建的数组,sizeof()函数应该返回 0。当我们加入一个新数组成员,sizeof()应该返回1。例1显示了我们想测试什么。
例1. 测试数组和sizeof()
<?php
$fixture = Array( );
// $fixture应该为空。
$fixture[] = "element";
// $fixture应该包含一个数组成员。
?>
最简单的测试方法是在加入数组成员前后打印sizeof()的运算结果,如果返回0和1,说明Array和sizeof()运行正常。
例2. 采用打印语句测试Array和sizeof()
<?php
$fixture = Array( );
print sizeof($fixture) . "\n";
$fixture[] = "element";
print sizeof($fixture) . "\n";
?>
0
1
现在,我们让测试程序从需要手工解释变为自动运行。在例3中,我们比较了期望值和实际值,如果相等就打印ok。如果我们发现有的结果不是ok,我们就知道有问题了。
例3. 比较Array和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
我们现在引入一个新的要素,如果期望值和实际值不同,我们就抛出一个异常。这样我们的输出就更简单了。如果测试成功,什么也不做,如果有一个未处理异常,我们知道有问题了。
例4.使用断言函数来测试Array和sizeof()
<?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 单元测试 从环境配置到 段元详细介绍
phpunit-clever-and-smart, 更智能的runner 测试 PHPUnit的智能测试 runner 任务通过在数据库中存储测试用例并按以下顺序在连续运行中重新排序测试来启用快速反馈周期:失败和错误迄今为止未记录的测试按执行时间( ...
**PHPUnit自动测试详解** 在软件开发中,错误是难以避免的。优秀程序员的标志在于他们能够通过测试有效地发现和修复这些问题。尽早发现错误意味着更低的修复成本,这也是为什么仅在软件发布前进行测试往往会导致...
phpunit-mock-objects, PHPUnit的模拟对象库 PHPUnit_MockObjectPHPUnit_MockObject 是PHPUnit默认的模拟对象库。要求PHP 5.6是必需的,但使用最新版本的PHP非常安装你可以使用 Composer 将这里库作为
网上找到的文档都是比较老旧的了,在官网上找到了最新版的中文手册,觉得还不错,分享给大家。 附上来源地址:https://phpunit.de/documentation.html PHPUnit中文站:...PHPUnit官方站:https://phpunit.de/
如果要从以前的版本升级,并且已在本地发布phpunit-printer.yml ,请确保将以下内容添加到选项部分 ... cd-printer-dont-format-classname : false ... 执行初始化脚本(可选) 以下步骤是可选的,但将为实现...
PHPUnit 是一个广泛使用的自动化测试框架,特别针对PHP编程语言。它的主要目的是为了简化和标准化软件测试过程,使得开发者能够高效地编写和执行单元测试。在本文中,我们将深入理解PHPUnit的核心概念和它如何应对...
phpunit-extensions 是 Etsy 的 PHPUnit 扩展。 标签:phpunit
本文主要关注的是PHPUnit中的装置器(Fixture)概念,它是测试中一个至关重要的部分。 装置器在测试中扮演着初始化和清理环境的角色,确保每次测试都在一个已知的、一致的状态下开始和结束。这种状态通常涉及到创建...
PHPUnit覆盖率检查工具安装composer require --dev iro88/phpunit-coverage-check用法示例根据文本输出检查 # using streamset -o pipefail && phpunit | phpunit-coverage-check --format=text 85.00# ...with ...
在Laravel框架中,PHPUnit是默认的单元测试工具,它为开发者提供了强大的测试能力。而Selenium WebDriver则是一个用于Web应用程序跨浏览器自动化测试的工具,它允许开发者模拟真实用户的行为来测试网页应用。当我们...
#### 第二章 测试环境搭建 为了进行接口自动化测试,首先需要搭建相应的测试环境。 - **PHP**:作为编码语言,其运行环境是必需的。 - **PHPUnit**:一种PHP的单元测试框架。 - **开发工具**:如JetBrains ...
phpunit-speedtrap, 在PHPUnit测试套件中,报告缓慢运行的测试 phpunit-speedtrap SpeedTrap报告你的控制台中PHPUnit测试套件中运行缓慢的测试。影响测试执行时间的许多因素。 测试没有正确地从变量延迟( 数据库,...
phpunit-github-actions-printer 在有一种零配置方式来实现这一这是一台PHPUnit打印机,使用GitHub Actions的::error和::warning功能为失败的测试运行添加注释。 与上述内容的主要区别在于,它支持添加除错误之外的...
phpunit-json-assertions PHPUnit的JSON断言包含特征/方法,以帮助通过各种方法验证JSON数据。 特征 通过JSON模式验证JSON数据 描述您现有的数据格式 清晰的,人为和机器可读的文档 完整的结构验证,对 自动化测试 ...
composer require --dev drawmyattention/phpunit-code-quality 将测试监听器注册到您的phpunit.xml文件: < object class = " DrawMyAttention\CodeQuality\ComplexityAnalyser " /> < bool>true ...
ci-phpunit-test, 一种简单的使用 PHPUnit 3.x 语言的方法 ci-phpunit-test用于 CodeIgniter 3 。x 在 CodeIgniter 3. x. 中使用PHPUnit的简便方法你根本不需要修改CodeIgniter核心文件。你可以轻松编
4. **集成到 TeamCity 构建流程**:通过 `phpunit-runner-teamcity`,可以在 TeamCity 的构建步骤中轻松配置和运行测试,与其他构建任务一起形成自动化流程。 5. **提高 CI 效率**:由于 TeamCity 能够直接理解测试...
phpunit-pretty-print :white_heavy_check_mark: 使您PHPUnit输出漂亮 安装 composer require sempro/phpunit-pretty-print --dev 该软件包需要>=7.0.0PHPUnit。 如果您在6.x运行,请使用1.0.3版。 如果您在9.x...