Write your first test: setUp(), naming conventions, assertEquals(), and expectException().
Your First PHPUnit Test
// src/Calculator.php
class Calculator {
public function add(int $a, int $b): int { return $a + $b; }
public function divide(int $a, int $b): float {
if ($b === 0) throw new DivisionByZeroError("Cannot divide by zero");
return $a / $b;
}
}
// tests/Unit/CalculatorTest.php
use PHPUnitFrameworkTestCase;
class CalculatorTest extends TestCase {
private Calculator $calc;
protected function setUp(): void {
$this->calc = new Calculator();
}
public function testAddReturnsCorrectSum(): void {
$this->assertEquals(5, $this->calc->add(2, 3));
$this->assertEquals(0, $this->calc->add(-1, 1));
}
public function testDivideByZeroThrowsException(): void {
$this->expectException(DivisionByZeroError::class);
$this->expectExceptionMessage("Cannot divide by zero");
$this->calc->divide(10, 0);
}
}
// Run
./vendor/bin/phpunit tests/Unit/CalculatorTest.php