Home  >  Article  >  Backend Development  >  How to write php unit tests

How to write php unit tests

尚
Original
2019-10-21 14:33:223741browse

How to write php unit tests

In the windows development environment, PHP unit testing can use PHPUnit.

Recommended reading: php server

Installing PHPUnit

Use composer to install PHPUnit. For other installation methods, please see here

composer require --dev phpunit/phpunit ^6.2

Install the Monolog log package for phpunit testing and logging.

composer require monolog/monolog

After installation, we can see that the coomposer.json file already has these two expansion packages:

"require": { 

    "monolog/monolog": "^1.23",

   },

"require-dev": {

       "phpunit/phpunit": "^6.2"

   },

Simple usage of PHPUnit

1. Single file test

Create the directory tests, create a new file StackTest.php, edit it as follows:

assertEquals(0, count($stack));
        array_push($stack, 'foo');
 
        // 添加日志文件,如果没有安装monolog,则有关monolog的代码都可以注释掉
        $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:

  1. StackTest is the test class

  2. StackTest inherits from PHPUnit\Framework\TestCase

  3. The test method testPushAndPop(), the test method must have public permissions, It usually starts with test, or you can choose to annotate it @test to indicate

  4. In the test method, an assertion method similar to assertEquals() is used to compare the actual value with An assertion is made on a match of expected values.

Command line execution:

phpunit command test file naming

 framework#  ./vendor/bin/phpunit tests/StackTest.php
 
// 或者可以省略文件后缀名
//  ./vendor/bin/phpunit tests/StackTest

Execution result:

➜  framework# ./vendor/bin/phpunit tests/StackTest.php
PHPUnit 6.4.1 by Sebastian Bergmann and contributors. 
.                                                                   1 / 1 (100%)
Time: 56 ms, Memory: 4.00MB
OK (1 test, 5 assertions)

The above is the detailed content of How to write php unit tests. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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