I wrote about unit testing in Objective-C when I was learning IOS development. Today I will summarize how to use unit testing in PHP.

One, foreword

In this article, we will use the dependency package management tool of Composer to install and manage phpUnit package. The official address of Composer is getcomposer.org/. We will also use a very useful Monolog logging component to record logs for our convenience.

To create the coomposer.json configuration file in the root directory, enter the following:



{
    "autoload": {
        "classmap": [
            ". /"]}}Copy the code

After executing Composer install on the command line, a vendor folder will be generated in the root directory, where any third-party code installed by composer will be generated.

Why unit tests?

Whenever you think of typing something into a print statement or debug expression, replace it with a test. –Martin Fowler

PHPUnit is open source software developed in the PHP programming language and is a unit testing framework. PHPUnit was created by Sebastian Bergmann and originated from Kent Beck’s SUnit as one of the frameworks in the xUnit family.

Unit testing is the process of testing individual code objects, such as functions, classes, and methods. Unit testing can be done using any piece of test code already written, or using existing testing frameworks such as JUnit, PHPUnit, or Cantata++. Unit testing frameworks provide a set of common and useful features to help people write automated testing units. For example, an assertion that checks whether an actual value matches our expected value. Unit testing frameworks often include reports for each test, along with the code coverage you’ve covered.

In a word, using PHPUnit for automatic testing will make your code more robust and reduce the cost of later maintenance. It is also a relatively standard specification. Nowadays, popular PHP frameworks include unit testing, such as Laraval,Symfony,Yii2, etc. Unit testing has become a standard.

In addition, the unit test case manipulates the test script by command, not by browser access to the URL.

3. Install PHPUnit

Use Composer to install PHPUnit, see here for other installation methods



composer require - dev phpunit/phpunit ^ 6.2Copy the code

Install Monolog log package for LOGGING of PHPUnit test.



composer require monolog/monologCopy the code

Once installed, we can see that the coomposer.json file already has these two extensions:



 "require": {  
     "monolog/monolog": "^ 1.23",},"require-dev": {
        "phpunit/phpunit": "^ 6.2"
    },
Copy the code

6. PHPUnit

1. Single file test

Create the tests directory and create a new stacktest.php file and edit it as follows:




        
2. Introduce the autoload.php file * 3. Test cases ** */
namespace App\tests;
require_once __DIR__ . '/.. /vendor/autoload.php';
define("ROOT_PATH", dirname(__DIR__)."/");

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

use PHPUnit\Framework\TestCase;


class StackTest extends TestCase
{
    public function testPushAndPop(a)
    {
        $stack = [];
        $this->assertEquals(0, count($stack));

        array_push($stack, 'foo');

        // Add log files. If monolog is not installed, the codes related to 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(a)
    {
        // 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; }}Copy the code

Code explanation:

  1. StackTest is the test class
  2. StackTest inheritance inPHPUnit\Framework\TestCase
  3. The test methodtestPushAndPop(), the test method must bepublicPermission, generally toThe test beginsOr you can choose to comment it@testTo the table
  4. In the test method, similar toassertEquals()Such an assertion method is used to assert a match between an actual value and an expected value.

Command line run the phpunit command to test file naming



➜  framework# ./vendor/bin/phpunit tests/StackTest.php

//Or you can omit the file suffix//  ./vendor/bin/phpunit tests/StackTestCopy the code

Execution Result:



➜ framework#./vendor/bin/ phpUnit tests/ stacktest.php phpUnit 6.4.1 by Sebastian Bergmann and Ficol3.. 1/1 (100%).Time: 56 ms, Memory: 4.00MB

OK (1 test, 5 assertions)Copy the code

We can view the log information we printed in the app.log file.

2. Class file introduction

Calculator.php




          
class Calculator  
{  
    public function sum($a, $b)  
    {  
        return$a + $b; }}? >  Copy the code

Unit test class: Calculatortest.php




        

namespace App\tests;
require_once __DIR__ . '/.. /vendor/autoload.php';
require "Calculator.php";

use PHPUnit\Framework\TestCase;


class CalculatorTest extends TestCase
{
    public function testSum(a)
    {
        $obj = new Calculator;
        $this->assertEquals(0, $obj->sum(0.0)); }}Copy the code

Command execution:



>./vendor/bin/phpunit tests/CalculatorTestCopy the code

Execution Result:



PHPUnit 6.4.1 by Sebastian Bergmann and FF1/3 (100%)Time: 117 ms, Memory: 4.00MB

There was 1 failure:Copy the code

$this->assertEquals(1, $obj->sum(0, 0)); See the execution result:



PHPUnit 6.41. by Sebastian Bergmann and contributors.

F                                                                   1 / 1 (100%)

Time: 117 ms, Memory: 4.00MB

There was 1 failure:

1) App\tests\CalculatorTest::testSum
Failed asserting that 0 matches expected 1.

/Applications/XAMPP/xamppfiles/htdocs/web/framework/tests/CalculatorTest.php:22

FAILURES!
Tests: 1.Assertions: 1.Failures: 1.Copy the code

Method error messages and line numbers are reported directly to help us find bugs quickly

3. Advanced usage

Are you tired of putting test in front of every test method name, or writing multiple test cases with different arguments? My favorite advanced feature, which I now recommend to you, is called the Framework Builder.

Calculator.php




          
class Calculator  
{  
    public function sum($a, $b)  
    {  
        return$a + $b; }}? >  Copy the code

The command line launches the test case using the keyword –skeleton



> ./vendor/bin/phpunit --skeleton Calculator.phpCopy the code

Execution Result:



PHPUnit 6.41. by Sebastian Bergmann and contributors.

Wrote test class skeleton for Calculator to CalculatorTest.php.  
Copy the code

Add the test data and re-execute the command




          
class Calculator  
{  
    / * * *@assertPhi of 0, 0 is equal to phi of 0 star@assert(0, 1) == 1 star@assert(1, 0) == 1 star@assert (1, 1) == 2 
     */  
    public function sum($a, $b)  
    {  
        return$a + $b; }}? >  Copy the code

Each method in the original class is tested with the @Assert annotation. These are turned into test code, like this



    /**
     * Generated from @assert (0, 0) == 0.
     */
    public function testSum(a) {
        $obj = new Calculator;
        $this->assertEquals(0, $obj->sum(0.0));
    }Copy the code

Execution Result:



./vendor/bin/ phpUnit tests/CalculatorTest phpUnit 6.4.1 by Sebastian Bergmann and ficol3.....Time: 0 seconds  
  
  
OK (4 tests)  Copy the code

4. Other usage

For other usage, please refer to the official website of PHPUnit China


Reference article: PHPUnit China official website documentation