PHP Unit Testing (PHPUnit)
PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.
1. Installation
The recommended way to install PHPUnit is via Composer.
composer require --dev phpunit/phpunit
2. Writing a Test
Tests are usually written in a class that extends PHPUnit\Framework\TestCase. The test methods must be public and start with test.
use PHPUnit\Framework\TestCase;
class StackTest extends TestCase {
public function testPushAndPop() {
$stack = [];
$this->assertSame(0, count($stack));
array_push($stack, 'foo');
$this->assertSame('foo', $stack[count($stack)-1]);
$this->assertSame(1, count($stack));
$this->assertSame('foo', array_pop($stack));
$this->assertSame(0, count($stack));
}
}
3. Common Assertions
Assertions are the checks that determine if the code behaves as expected.
$this->assertTrue($condition): Check if true.$this->assertFalse($condition): Check if false.$this->assertEquals($expected, $actual): Check if values are equal.$this->assertSame($expected, $actual): Check if values and types are equal (===).$this->assertCount($count, $haystack): Check array count.
4. Running Tests
You can run tests using the PHPUnit binary installed by Composer.
./vendor/bin/phpunit tests/StackTest.php