Home > Article > Backend Development > Unit testing and coverage analysis of PHP functions
Unit testing and coverage analysis of PHP functions: Use PHPUnit for unit testing, writing .test.php files to isolate and test individual functions. Use the phpunit command to run unit tests. Use phpunit --coverage-html to analyze coverage and generate a report showing tested and untested lines of code. Installing PHPUnit, writing unit tests, running the tests, analyzing coverage, demonstrating this process using a custom add function.
Unit testing and coverage analysis of PHP functions
Writing high-quality code in PHP requires rigorous testing. to ensure it functions correctly and achieves expected results. Unit testing provides a way to isolate and test individual functions or methods, while coverage analysis helps determine which parts of the code have been tested.
Installing PHPUnit
PHPUnit is a popular PHP unit testing framework. To install it, use Composer:
composer require --dev phpunit/phpunit
Writing Unit Tests
Unit tests are written using a file with a .test.php extension. The following is an example of testing the add function:
<?php use PHPUnit\Framework\TestCase; class AddFunctionTest extends TestCase { public function testAddNumbers() { $result = add(1, 2); $this->assertEquals(3, $result); } }
Run the unit test
Use the phpunit command to run the unit test:
phpunit
Analyze coverage Rate
Phpunit provides a built-in option to generate a coverage report:
phpunit --coverage-html
This will generate a coverage report under the html
directory. It will show which lines in the code have been tested and which lines have not been tested.
Practical case
To demonstrate, we create a custom add function and then write a unit test to test it:
functions .php
<?php function add(int $num1, int $num2): int { return $num1 + $num2; }
AddFunctionTest.test.php
<?php use PHPUnit\Framework\TestCase; class AddFunctionTest extends TestCase { public function testAddNumbers() { $result = add(1, 2); $this->assertEquals(3, $result); } public function testAddNegativeNumbers() { $result = add(-1, -2); $this->assertEquals(-3, $result); }
Run unit tests:
phpunit
Generate coverage report:
phpunit --coverage-html
The coverage report will show that the add
function is fully covered, which means that all of its code paths are covered by our unit tests.
The above is the detailed content of Unit testing and coverage analysis of PHP functions. For more information, please follow other related articles on the PHP Chinese website!