PHPUnit
PHPUnit is a unit testing framework, similar to JUnit in Java.
- π Documentation
- π¦ GitHub (19k β)
You will define classes with one or more tests (TestCase
) that use assertions that check that a condition is valid or raise an error.
You can install PHPUnit using composer
$ composer require --dev phpunit/phpunit^9.5
To run tests, you can use
$ ./vendor/bin/phpunit test_file.php
TestCases
A basic test class:
<?php declare(strict_types=1);
use PHPUnit\Framework\TestCase;
class XXXTest extends TestCase {
public function testXXX() : void {
// code...
}
// more tests...
}
You can execute some code before/after all tests
// ...
class XXXTest extends TestCase {
// ...
public static function setUpBeforeClass(): void {}
public static function tearDownAfterClass(): void {}
}
You can execute some code before/after each test
// ...
class XXXTest extends TestCase {
// ...
protected function setUp(): void {}
protected function tearDown(): void {}
}
Inside a test, here are examples of assertions you can use:
// boolean true/false
$this->assertTrue($condition);
$this->assertFalse($condition);
// equals
$this->assertEquals($expected, $value);
$this->assertNotEquals($expected, $value);
// empty
$this->assertEmpty($value);
$this->assertNotEmpty($value);
// type
$this->assertIsArray($value);
$this->assertIsInt($value);
$this->assertIsNotBool($value);
$this->assertInstanceOf($expected, $value);
// ...
// reference
$this->assertSame($expected, $value);
$this->assertNotSame($expected, $value);
// size
$this->assertCount($expected_size, $tab);
$this->assertNotCount($expected_size, $tab);