PHPUnit is the standard testing framework for PHP. Write test methods that use assertions like assertEquals() to verify your code works correctly. Run tests with vendor/bin/phpunit to catch bugs before production.
PHPUnit Testing
// composer require --dev phpunit/phpunit
use PHPUnit\Framework\TestCase;
class CalculatorTest extends TestCase {
private Calculator $calc;
protected function setUp(): void {
$this->calc = new Calculator();
}
public function testAdd(): void {
$this->assertEquals(5, $this->calc->add(2, 3));
}
public function testDivideByZero(): void {
$this->expectException(DivisionByZeroError::class);
$this->calc->divide(10, 0);
}
/** @dataProvider additionProvider */
public function testAddData(int $a, int $b, int $expected): void {
$this->assertEquals($expected, $this->calc->add($a, $b));
}
public static function additionProvider(): array {
return [[1, 2, 3], [0, 0, 0], [-1, 1, 0]];
}
}
// Run: ./vendor/bin/phpunit tests/