Unit Testing (PHP)
Installation
Let’s install PHP through XAMPP. If needed, add it to $PATH
echo "export PATH=/opt/lampp/bin:$PATH" >> ~/.bashrc
Option 1
Install Composer and require PHPUnit as a development dependency:
composer require --dev phpunit/phpunit
… Run the test! Run PHPUnit from the project’s directory
./vendor/bin/phpunit test/test.php
Option 2
Download the PHPUnit PHAR file and move it to your user-level scripts directory:
wget https://phar.phpunit.de/phpunit.phar && chmod +x phpunit.phar && sudo mv phpunit.phar ~/bin/phpunit
… Run the test! Run PHPUnit from user-level scripts directory
phpunit test/test.php
Unit testing sample
Function example src/functions.php
<?php
function helloWorld() {
return "Hello, World!";
}
Test example test/test.php
<?php
use PHPUnit\Framework\TestCase;
class FunctionsTest extends TestCase
{
public function testHelloWorld()
{
require 'src/functions.php';
$this->assertEquals("Hello, World!", helloWorld());
}
}
Assumed project structure
myProject/
├── src
│ └── functions.php
└── test
└── test.php