📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Testing with PHPUnit

Testing with PHPUnit

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

Test your understanding before moving on

1. What testing framework is standard for PHP?
💡 PHPUnit is the de-facto standard testing framework for PHP.
2. PHPUnit test class methods must:
💡 PHPUnit discovers tests by finding public methods starting with test.
3. Which PHPUnit method checks two values are equal?
💡 assertEquals() checks two values are loosely equal; assertSame() uses strict comparison.
4. What is a data provider in PHPUnit?
💡 Data providers (annotated with @dataProvider) supply multiple sets of arguments to a test.
5. Which method runs before each test?
💡 setUp() is called before each test method in the class.