PHP

PHP Unit Testing with PHPUnit

Write comprehensive unit tests covering mocking, data providers, and code coverage analysis.

PHPPHPUnitTestingTDD

Thumbnail for PHP Unit Testing with PHPUnit

Overview

Write comprehensive unit tests covering mocking, data providers, and code coverage analysis.

Key Concepts

This project covers essential PHP development patterns including object-oriented programming, database interaction, and security best practices.

Getting Started

bash
# Clone the repository
git clone https://github.com/example/php-16-php-unit-testing-with-phpunit
cd php-16-php-unit-testing-with-phpunit

# Start local server
php -S localhost:8000

Core Implementation

php
<?php
declare(strict_types=1);

namespace App;

class PHPService
{
    private \PDO $db;

    public function __construct(\PDO $db)
    {
        $this->db = $db;
    }

    public function findAll(): array
    {
        $stmt = $this->db->query("SELECT * FROM items ORDER BY created_at DESC");
        return $stmt->fetchAll(\PDO::FETCH_ASSOC);
    }

    public function create(array $data): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO items (title, content, status) VALUES (:title, :content, :status)"
        );
        $stmt->execute([
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
            ':status'  => $data['status'] ?? 'draft',
        ]);
        return (int) $this->db->lastInsertId();
    }

    public function update(int $id, array $data): bool
    {
        $stmt = $this->db->prepare(
            "UPDATE items SET title = :title, content = :content WHERE id = :id"
        );
        return $stmt->execute([
            ':id'      => $id,
            ':title'   => htmlspecialchars($data['title']),
            ':content' => htmlspecialchars($data['content']),
        ]);
    }
}
?>

Database Schema

sql
CREATE TABLE items (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT,
    status ENUM('draft', 'published', 'archived') DEFAULT 'draft',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    INDEX idx_status (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Security Considerations

- All user inputs are sanitized with \htmlspecialchars()\ - Database queries use prepared statements to prevent SQL injection - CSRF tokens are validated on all form submissions - Sessions are configured with \httponly\ and \secure\ flags

Tags

- PHP - PHPUnit - Testing - TDD

Related Projects

Comments (0)

Leave a Comment

No comments yet. Be the first to comment!