I used to learn iOS development with a dedicated unit test written objective-c, iOS Development Learning Unit test, and today to summarize how to use unit testing in PHP.
First, preface
In this article, we use composer
the dependency Package management tool for phpunit
package installation and management, composer official address https://getcomposer.org/, follow the prompts for global installation, in addition, We also use a very useful monolog logging component to log logs for easy viewing.
In the configuration file created under the root directory coomposer.json
, enter the following:
{" autoload": { "Classmap": [ "./" ] }}
The above means that all of the root directory will be 类文件
loaded in, after the command line execution composer install
, the root directory will generate a vendor
folder, we will later composer
install any third-party code is generated here.
Second, why should unit test?
whenever you think of entering something into a print statement or a debug expression, use the test instead. --martin Fowler
PHPUnit
is an open source software developed in the PHP programming language, is a unit testing framework. The PHPUnit was created by Sebastian Bergmann, a sunit from Kent Beck, one of the Xunit family's frameworks.
Unit testing is the process of testing a separate code object, such as testing a function, class, or method. Unit tests can use any test code that has already been written, or you can use some existing test frameworks, such as JUnit, PHPUnit, or cantata++, and the unit Test framework provides a series of common, useful functions to help people write automated detection units. For example, an assertion that checks whether an actual value conforms to the value we expect. The unit test framework often contains reports for each test and gives you coverage of the code that you have covered.
In short, the use of phpunit
automated testing will make your code more robust, reduce the cost of late maintenance, but also a standard specification, now popular PHP framework with unit testing, such as LARAVAL,SYMFONY,YII2, Unit testing has become standard.
In addition, a unit test case is a command-controlled test script, rather than a URL that is accessed through a browser.
Third, installation PHPUnit
composer
install PHPUnit using the method, other installation methods please see here
Composer require--dev Phpunit/phpunit ^6.2
Install Monolog Log package, do phpunit test logging.
Composer require Monolog/monolog
Once installed, we can see coomposer.json
that the files already have these two expansion packs:
"Require": { "Monolog/monolog": "^1.23", }, "Require-dev": { "phpunit/phpunit": "^6.2" },
Iv. Simple usage of phpunit
1. Single File test
Create a directory tests
, new file StackTest.php
, edit as follows:
<?php/** * 1, composer install monolog log extension, install PHPUnit Unit Test Expansion pack * 2, introduce autoload.php file * 3, Test case * * */namespace app\tests;require_o nCE __dir__. '/.. /vendor/autoload.php ';d efine ("Root_path", DirName (__dir__). "/"); use Monolog\logger;use monolog\handler\streamhandler;use phpunit\framework\testcase;class StackTest extends testcase{Public Function Testpushandpop () {$stack = []; $this->assertequals (0, Count ($stack)); Array_push ($stack, ' foo '); Add log files, if not installed Monolog, then the code about Monolog can be commented out $this->log ()->error (' Hello ', $stack); $this->assertequals (' foo ', $stack [count ($stack)-1]); $this->assertequals (1, Count ($stack)); $this->assertequals (' foo ', Array_pop ($stack)); $this->assertequals (0, Count ($stack)); Public Function log () {//Create a log channel $log = new Logger (' Tester '); $log->pushhandler (New Streamhandler (Root_path. ' Storage/logs/app.log ', logger::warning)); $loG->error ("error"); return $log; }}
Code Explanation:
Stacktest for Test class
Stacktest inherits fromPHPUnit\Framework\TestCase
Test method testPushAndPop()
, the test method must be a public
permission, generally test开头
, or you can also choose to add comments @test
to the table
Within the test method, assertEquals()
an assertion method similar to this is used to assert the match between the actual value and the expected value.
Command line execution:
PHPUnit Command test file naming
➜ framework# ./vendor/bin/phpunit tests/stacktest.php//or you can omit the file suffix name// ./vendor/bin/phpunit tests/ Stacktest
Execution Result:
➜ framework#./vendor/bin/phpunit tests/stacktest.phpphpunit 6.4.1 by Sebastian Bergmann and contributors . 1/1 (100%) time:56 MS, Memory:4.00mbok (1 Test, 5 assertions)
We can app.log
view our printed log information in the file.
2. Introduction of class Files
calculator.php
<?php class Calculator {public function sum ($a, $b) { return $a + $b; } } ? >
Unit Test class:
calculatortest.php
<?phpnamespace app\tests;require_once __dir__. '/.. /vendor/autoload.php '; require "calculator.php"; use Phpunit\framework\testcase;class Calculatortest extends TestCase {Public function testsum () { $obj = new Calculator; $this->assertequals (0, $obj->sum (0, 0));} }
Command execution:
>./vendor/bin/phpunit tests/calculatortest
Execution Result:
PHPUnit 6.4.1 by Sebastian Bergmann and contributors. F 1/1 (100%) time:117 MS, Memory:4.00mbthere was 1 failure:
If we write this assertion deliberately wrong,$this->assertEquals(1, $obj->sum(0, 0));
See execution results:
PHPUnit 6.4.1 by Sebastian Bergmann and contributors. F 1/1 (100%) time:117 MS, Memory:4.00mbthere was 1 failure:1) app\tests\calculatortest::testsumfailed asserting tha T 0 matches expected 1./applications/xampp/xamppfiles/htdocs/web/framework/tests/calculatortest.php:22failures! Tests:1, Assertions:1, failures:1.
Will report the method error message and line number directly, help us to quickly find out the bug
3. Advanced usage
Are you tired of having to put a test in front of each method name, or is it a struggle to write multiple test cases just because the arguments are different? My favorite advanced features, now solemnly recommended to you, called 框架生成器
.
calculator.php
<?php class Calculator {public function sum ($a, $b) { return $a + $b; } } ? >
command line to start the test case, using the keyword--skeleton
>./vendor/bin/phpunit--skeleton calculator.php
Execution Result:
PHPUnit 6.4.1 by Sebastian Bergmann and contributors. Wrote test class skeleton for Calculator to calculatortest.php.
is not very simple, because there is no test data, so add test data here, and then re-execute the top command
<?php class Calculator { /** * @assert (0, 0) = = 0 * @assert (0, 1) = = 1 * @assert (1, 0) = = 1 * @assert (1, 1) = = 2 * /Public function sum ($a, $b) { return $a + $b; } } ? >
Each method in the original class is instrumented for @assert annotations. These are turned into Test code, like this
/** * Generated from @assert (0, 0) = = 0. * /Public Function testsum () { $obj = new Calculator; $this->assertequals (0, $obj->sum (0, 0)); }
Execution Result:
./vendor/bin/phpunit tests/calculatortestphpunit 6.4.1 by Sebastian Bergmann and contributors. .... time:0 seconds OK (4 tests)