SyntaxStudy
Sign Up
PHP Writing Unit Tests
PHP Beginner 4 min read

Writing Unit Tests

Unit Tests

Unit tests isolate a single class or function. Test one thing per test, name tests to describe behaviour, and follow Arrange-Act-Assert.

Example
class CartTest extends TestCase {
    public function test_adding_item_updates_total(): void {
        // Arrange
        $cart = new Cart();
        $item = new CartItem("Widget", 9.99, 2);
        // Act
        $cart->add($item);
        // Assert
        $this->assertSame(19.98, $cart->total());
        $this->assertCount(1, $cart->items());
    }
}
// Pest equivalent
it("updates total when item added", function () {
    $cart = new Cart();
    $cart->add(new CartItem("Widget", 9.99, 2));
    expect($cart->total())->toBe(19.98);
});
Pro Tip

A test method should have one reason to fail — multiple assertions are fine if they test the same behaviour.