Unit testing is a software testing technique where individual units or methods of a program are tested independently to ensure they work properly. A unit test verifies that a specific code section behaves as expected, helping developers catch bugs early and improve code quality.
PHPUnit is a popular testing framework for PHP, allowing developers to write and run unit tests efficiently. Follow the steps below to install PHPUnit on Windows, Linux, and macOS.
composer require --dev phpunit/phpunit
vendor\bin\phpunit --version
phpunit.phar
from the official site.C:\phpunit
).C:\phpunit
to your system’s PATH
.php phpunit.phar --version
curl -sS https://getcomposer.org/installer | php mv composer.phar /usr/local/bin/composer
composer require --dev phpunit/phpunit
vendor/bin/phpunit --version
wget -O phpunit https://phar.phpunit.de/phpunit.phar chmod +x phpunit sudo mv phpunit /usr/local/bin/phpunit
phpunit --version
Create a new directory for your project:
mkdir phpunit-demo && cd phpunit-demo
Initialize a new composer project:
composer init --no-interaction
Install PHPUnit:
composer require --dev phpunit/phpunit
Create a tests
directory and add a test file:
mkdir tests nano tests/ExampleTest.php
Add the following code inside tests/ExampleTest.php
:
<?php use PHPUnit\Framework\TestCase; class ExampleTest extends TestCase { public function testAddition() { $this->assertEquals(4, 2 + 2); } }
Execute the test using:
./vendor/bin/phpunit tests
Expected output:
OK (1 test, 1 assertion)
This article introduced unit testing, installed PHPUnit on various operating systems, and set up a basic project with a simple test case. In the next part of this series, we will explore more advanced PHPUnit features, including test assertions, test doubles, and best practices.