When I was learning IOS development, I wrote an article specifically about unit testing in Objective-C. Unit testing for learning IOS development. Today I will summarize how to use unit testing in PHP.
1. Preface
In this article, we use the dependency package management tool of composer
to install and manage phpunit
packages , the official address of composer is https://getcomposer.org/, just follow the prompts to install it globally. In addition, we will also use a very easy-to-use Monolog logging component to record logs for our convenience.
Create the coomposer.json
configuration file in the root directory and enter the following content:
{ "autoload": { "classmap": [ "./" ] } }
The above means that all classes in the root directory will be Files
are loaded in. After executing composer install
on the command line, a vendor
folder will be generated in the root directory. We will use composer
in the future. Any third-party code installed will be generated here.
2. Why unit testing?
Any time you think of typing something into a print statement or debug expression, replace it with a test. --Martin Fowler
PHPUnit
is an open source software developed in the PHP programming language and is a unit testing framework. PHPUnit was created by Sebastian Bergmann, derived from Kent Beck's SUnit, and is one of the frameworks of the xUnit family.
Unit testing is the process of testing individual code objects, such as testing functions, classes, and methods. Unit testing can use any piece of test code that has been written, or you can use some existing testing frameworks, such as JUnit, PHPUnit or Cantata++. The unit testing framework provides a series of common and useful functions to help people write automated detection units. , such as an assertion that checks whether an actual value matches the expected value. Unit testing frameworks often include reports for each test and give you the code coverage you have 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 and is a popular PHP framework today. They all come with unit testing, such as Laraval, Symfony, Yii2, etc. Unit testing has become standard.
In addition, unit test cases control the test script through commands instead of accessing the URL through the browser.
3. Install 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 and make phpunit test records For 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" },
4. Simple usage of PHPUnit
1. Single file test
Create directorytests
, create a new fileStackTest.php
, edit 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
Test method
testPushAndPop()
, the test method must havepublic
permissions, usually starting withtest
, or you can choose to give it Add comment@test
to indicateIn 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)
We can View the log information we printed in the app.log
file.
2. Class file introduction
Calculator.php
<?php class Calculator { public function sum($a, $b) { return $a + $b; } } ?>
Unit test class:
CalculatorTest.php
<?php namespace 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.00MB There was 1 failure:
If we deliberately write the assertion here wrong, $this->assertEquals(1, $obj->sum(0, 0));
Look at the execution results:
PHPUnit 6.4.1 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.
will directly report the method error message and line number, which will help us quickly find the bug
3. Advanced usage
Are you tired of adding test in front of each test method name? Are you struggling to write multiple test cases because the parameters you call are different? My favorite advanced feature, which I now recommend to you, is called Framework Generator
.
Calculator.php
<?php class Calculator { public function sum($a, $b) { return $a + $b; } } ?>
Command line to start the test case, use 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.
Isn’t it very simple, because there is no test data, so add test data here, and then re-execute the above 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; } } ?>
Every method in the original class is tested for the @assert annotation. 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 results:
The above is the detailed content of How to use PHP unit testing framework PHPUnit. For more information, please follow other related articles on the PHP Chinese website!

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

PHPisusedforsendingemailsduetoitsbuilt-inmail()functionandsupportivelibrarieslikePHPMailerandSwiftMailer.1)Usethemail()functionforbasicemails,butithaslimitations.2)EmployPHPMailerforadvancedfeatureslikeHTMLemailsandattachments.3)Improvedeliverability

PHP performance bottlenecks can be solved through the following steps: 1) Use Xdebug or Blackfire for performance analysis to find out the problem; 2) Optimize database queries and use caches, such as APCu; 3) Use efficient functions such as array_filter to optimize array operations; 4) Configure OPcache for bytecode cache; 5) Optimize the front-end, such as reducing HTTP requests and optimizing pictures; 6) Continuously monitor and optimize performance. Through these methods, the performance of PHP applications can be significantly improved.

DependencyInjection(DI)inPHPisadesignpatternthatmanagesandreducesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itallowspassingdependencieslikedatabaseconnectionstoclassesasparameters,facilitatingeasiertestingandscalability.

CachingimprovesPHPperformancebystoringresultsofcomputationsorqueriesforquickretrieval,reducingserverloadandenhancingresponsetimes.Effectivestrategiesinclude:1)Opcodecaching,whichstorescompiledPHPscriptsinmemorytoskipcompilation;2)DatacachingusingMemc


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
