Home > Backend Development > PHP Tutorial > Using PHPUnit for PHP unit testing_PHP tutorial

Using PHPUnit for PHP unit testing_PHP tutorial

WBOY
Release: 2016-07-20 11:13:56
Original
752 people have browsed it

PHPUnit是一个用PHP编程语言开发的开源软件,是一个单元测试框架。PHPUnit由Sebastian Bergmann创建,源于Kent Beck的SUnit,是xUnit家族的框架之一。本文将探索PHPUnit,特别介绍自动化单元测试的基本用法。你需要掌握PHP编程语言的基本知识 才能继续。

作者:Kendrick Curtis,Stainless Software, http://www.stainless-software.com/

介绍

单元测试是对单独的代码对象进行测试的过程,比如对函数、类、方法进行测试。单元测试可以使用任意一段已经写好的测试代码,也可以使用一些已经存在的测试 框架,比如JUnit、PHPUnit或者Cantata++,单元测试框架提供了一系列共同、有用的功能来帮助人们编写自动化的检测单元,例如检查一个 实际的值是否符合我们期望的值的断言。单元测试框架经常会包含每个测试的报告,以及给出你已经覆盖到的代码覆盖率。

Using PHPUnit for PHP unit testing_PHP tutorial
Using PHPUnit for PHP unit testing_PHP tutorial
翻译于 昨天(9:23)

2人顶

 翻译的不错哦!

PHPUnit is an open source software developed in the PHP programming language and is a unit testing framework. PHPUnit was created by Sebastian Bergmann, derived from Kent Beck's SUnit, and is one of the frameworks of the xUnit family. This article will explore PHPUnit, specifically introducing the basic usage of automated unit testing. You will need basic knowledge of the PHP programming language to proceed.
安装

PHPUnit 通常以 PEAR 包,Composer bundle 或是 PHAR 文件形式存在。如果你要安装它,你需要先安装 PHP Code Coverage 依赖。在 PEAR 中,你需要天价 phpunit.de 频道,并通过命令行安装两个包:

PHP Unit Testing with PHPUnit
(注意,在输入时,默认的 XAMPP 的 PEAR 安装已经被破坏:你需要在尝试上面代码之前先安装 PEAR PHAR)。

测试一个简单的类

试试只有单一方法的简单类:

1 class TruthTeller
2 {
Author: Kendrick Curtis, Stainless Software, http://www.stainless-software.com/
3 public function() tellTruth

Introduction

4 {
Unit testing is the process of testing individual code objects, such as testing functions, classes, and methods. Unit testing can use any piece of test code that has been written, or you can use some existing testing frameworks, such as JUnit, PHPUnit or Cantata++. The unit testing framework provides a series of common and useful functions to help people write automated detection units. , such as an assertion that checks whether an actual value matches the expected value. Unit testing frameworks often include reports for each test and give you the code coverage you have covered.
5 return true;
6 }
7 }
Using PHPUnit for PHP unit testing_PHP tutorial

Using PHPUnit for PHP unit testing_PHP tutorial

Translated yesterday (9:23)
2Using PHPUnit for PHP unit testing_PHP tutorial Likes

Like

Nice translation!

PHP Unit Testing with PHPUnit (Note, at the time of typing, the default XAMPP PEAR installation is broken: you need to install PEAR PHAR before trying the above code).

Test a simple class

Installation PHPUnit usually exists in the form of PEAR package, Composer bundle or PHAR file. If you want to install it, you need to install the PHP Code Coverage dependency first. In PEAR, you need the phpunit.de channel and install both packages via the command line:
Try a simple class with a single method:
使用PHPUnit,每组测试是PHPUnit_Framework_TestCase类的一个扩展类,它提供了常用的功能,如判断。下面是一个对上述tellTruth方法的一个基本测试:
01 require_once 'PHPUnit/Autoload.php';
1
02 require_once 'TruthTeller.class.php';
class TruthTeller Yes, now the tellTruth method always returns TRUE, so how should we use unit testing to ensure that its return value remains unchanged in the future? Using PHPUnit for PHP unit testing_PHP tutorialTranslated yesterday (14:12) 1Liked Like Nice translation!
Using PHPUnit, each set of tests is an extension class of the PHPUnit_Framework_TestCase class, which provides common functions such as judgment. Here is a basic test of the above tellTruth method:
01 require_once 'PHPUnit/Autoload.php'; <table> <tbody> <tr> <td class="number"> <code>02 require_once 'TruthTeller.class.php'; <table> <tbody> <tr> <td class="number"><code>03 class TruthTester extends PHPUnit_Framework_TestCase
04 {
05 function testTruthTeller()
06 {
07 $tt = new TruthTeller();
08 $this->assertTrue($tt->tellTruth());
09 }
10 }

Please note that you need to include PHPUnit's autoloader and the "object under test", in this case the TruthTeller class file.

Using PHPUnit for PHP unit testing_PHP tutorial
Yuanyuan Xiaoyi
Translated yesterday (10:18)

0Likes

Like Nice translation!

如果你启动了命令行提示,切换到你的测试所在目录,运行 phpunit TruthTester (参数是你的测试文件名,去除 .php 扩展名),PHPUnit 将会运行文件中指定的所有它能找到的测试(测试将是名字以 test 开头的所有方法)。

PHP Unit Testing with PHPUnit

如果你回到 TruthTeller 类,并将其方法的返回值改为 FALSE,你讲看到类似下面的信息:

PHP Unit Testing with PHPUnit

这就是单元测试的核心——编写断言并判断是否通过。当先前编写并测试通过的代码开始无法通过时,你就知道有更改的代码对现有代码起了负面影响。

Using PHPUnit for PHP unit testing_PHP tutorial
Using PHPUnit for PHP unit testing_PHP tutorial
翻译于 昨天(14:22)

0人顶

 翻译的不错哦!

If you start the command line prompt, switch to the directory where your test is located, run phpunit TruthTester (the parameter is your test file name, remove the .php extension), PHPUnit will run all the files specified in the file it can find. of tests (tests will be all methods whose names start with test).
更复杂的测试

在现实中,你肯定需要处理比上一个更复杂的情况。比如一个常见的测试是检查下面的outputArray方法是否返回了一个特定数据结构的数组。

1 class ArrayTeller
2 {
PHP Unit Testing with PHPUnit
3 public function outputArray()
4 {
If you go back to the TruthTeller class and change the return value of its method to FALSE, you will see a message similar to the following: PHP Unit Testing with PHPUnit This is the core of unit testing - writing assertions and judging whether they pass or not. You know that changed code has a negative impact on existing code when code that you previously wrote and tested begins to fail. Using PHPUnit for PHP unit testing_PHP tutorial Using PHPUnit for PHP unit testing_PHP tutorialTranslated yesterday (14:22) 0Likes Like Nice translation!
More complex tests In reality, you will definitely need to deal with more complex situations than the last one. For example, a common test is to check whether the outputArray method below returns an array of a specific data structure.
1 class ArrayTeller
2 {
3 public function outputArray()
4 {
5 return array(1,2,3);
6 }
7 }

A simple test for this method could be written like this:

01 class ArrayTester extends PHPUnit_Framework_TestCase
02 {
03 function testArrayTeller()
04 {
05 $at = new ArrayTeller();
06 $result = $at->outputArray(1);
07 $this->assertInternalType("array", $result);
08 $this->assertCount(3, $result);
09 $this->assertEquals(1, $result[0]);
10 $this->assertEquals(3, $result[2]);
11 }
12 }

As you can see, when using PHPUnit for unit testing, you can perform a variety of checks on each line: you can check whether the ArrayTeller returns an array, not any other data class Type; can check the length of an array; can check a single value in an array. In addition to these, there are other functional assertions. For example, if you need more complex judgments, suppose you want to know whether a return value is between two integers. Within the range of numbers, as long as you can express it by the result of an IF statement, you can use the assertion assertTrue to test the result. You can click on the following link to access the list of all available assertions in the PHPUnit official website documentation.

Using PHPUnit for PHP unit testing_PHP tutorial
Zhao Liang-myself
Translated yesterday (14:25)

0Likes

Like Nice translation!

Other translations(1)
测试代码路径

单元测试片面的讲就是编写覆盖被测方法所有预期行为的测试,最好基于规范文档,不过如果你在编写覆盖现有代码的单元测试,将其视为白盒测试的一种形式更有用。如果你知道一个如下的简单切换方法:

01 class Switcher
02 {
03   public function aOrB($switch, $a, $b)
04   {
05     if ($switch == TRUE)
06     {
07       return $a;
08     }
09     else
10     {
11       return $b;
12     }
13   }
14 }

… then you know you need to write two tests, one for each situation. But you start to question how you know this - if the method later becomes True it returns $a, False returns $b, otherwise throws an exception, ideally it's mentioned somewhere in the spec document. Anyway, the test of the above method is as follows:

01 class SwitcherTester extends PHPUnit_Framework_TestCase
02   {
03     function testSwitchTrue()
04     {
05       $switcher = new Switcher();
06       $result = $switcher->aOrB(TRUE, 1, 2);
07       $this->assertEquals(1, $result);
08     }
09     function testSwitchFalse()
10     {
11       $switcher = new Switcher();
12       $result = $switcher->aOrB(FALSE, 1, 2);
13       $this->assertEquals(2, $result);
14     }
15 }

Running both tests is as easy as running phpunit SwitcherTester from the command line.

Using PHPUnit for PHP unit testing_PHP tutorial
Using PHPUnit for PHP unit testing_PHP tutorial
Translated yesterday (14:46)

0Likes

Like Nice translation!

Use setUp to simplify multiple tests
使用 setUp,简化多个测试

当你的测试需要覆盖越来越多的输入组合及数据设置时,使用函数: setUp 将会非常有帮助。setUp 是 PHPUnit_Framework_TestCase 类中你可以覆写以在类中所有及每个测试运行前运行的代码。(注意,还有一个简单的方法,tearDown,它会在所有测试结束后立即运行——这对关闭 socket 及文件指针很有帮助)

下面是如何精简代码的一个简单的例子。尝试一个依赖一些对象数据何输入的方法。

01 class DataTeller
When your tests need to cover more and more input combinations and data settings, using the function: setUp will be very helpful. setUp is PHPUnit_Framework_TestCase Code within a class that you can override to run before all and every test in the class is run. (Note that there is also a simple method, tearDown, which runs immediately after all tests have finished - this is useful for closing socket and file pointers are helpful)
02   {
03   private $data;
Here is a simple example of how to streamline your code. Try a method that relies on some object data and input.
01 class DataTeller
02 {
03 private $data;
04   public function __construct($data)
05   {
06     $this->data = $data;
07   }
08   public function outputData($switch)
09   {
10     if ($switch == TRUE)
11     {
12       if (!empty($this->data))
13         return $this->data;
14       else
15         return FALSE;
16     }
17     else
18     {
19       return "switch off";
20     }
21   }
22 }

If you continue with the naive approach from before, we need to write three tests and instantiate three DataTeller objects, once for each test. However, by setUp, we can outsource the creation of DataTellers objects, at least two of the three. Only the last test requires a new DataTeller to be created.

01 class DataTellerTester extends PHPUnit_Framework_TestCase
02 {
03   private $dt;
04   protected $data = "valid data";
05   function setUp()
06   {
07     $this->dt = new DataTeller($this->data);
08   }
09   function testOutputArraySwitchOff()
10   {
11     $this->assertEquals("switch off", $this->dt->outputData(FALSE));
12   }
13   function testOutputArraySwitchOn()
14   {
15     $this->assertEquals($this->data, $this->dt->outputData(TRUE));
16   }
17   function testOutputArrayEmptySwitchOn()
18   {
19     $new_dt = new DataTeller("");
20     $this->assertEquals(FALSE, $new_dt->outputData(TRUE));
21   }
22 }
Using PHPUnit for PHP unit testing_PHP tutorial
Using PHPUnit for PHP unit testing_PHP tutorial
Translated yesterday (15:03)

0Likes

Like Nice translation!

Conclusion

PHPUnit uses assertions to tell you whether the code you are testing is working as you expect. After learning this, you should now be able to write some simple tests to cover some classes with relatively independent functions. But the real challenge comes when you want to test classes that interact with each other. To do this, listen to the next tutorial to learn how to write tests for static classes and how to use mocks and Stubs (stubs, stubs) to isolate the object you want to test from other code in its environment.

Extended reading

* PHPUnit manual
* PHPUnit tutorial on PEAR site

About the author

Kendrick Curtis is a web developer with ten years of experience. He is the founder of Stainless Software, a company that provides contract web design, development, testing and content creation. More information can be found on its company website: http://www.stainless-software.com/

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/440325.htmlTechArticlePHPUnit is an open source software developed with the PHP programming language and is a unit testing framework. PHPUnit was created by Sebastian Bergmann, derived from Kent Beck's SUnit, and is one of the frameworks of the xUnit family. ...

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template