📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHPUnit Testing Writing Your First Test

Writing Your First Test

5 min read Quiz at the end
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
Topic Quiz · 2 questions

Test your understanding before moving on

1. What is the AAA pattern in testing?
💡 AAA: Arrange (setup), Act (run code), Assert (verify results).
2. What does expectException() do?
💡 expectException(SomeException::class) tells PHPUnit the test should throw that exception.