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:
<?php /** * 1、composer 安装Monolog日志扩展,安装phpunit单元测试扩展包 * 2、引入autoload.php文件 * 3、测试案例 * * */ 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() { $stack = []; $this->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:
StackTest is the test class
StackTest inherits from PHPUnit\Framework\TestCase
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
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!