Convert Figma logo to code with AI

sebastianbergmann logophpunit

The PHP Unit Testing framework.

19,683
2,199
19,683
103

Top Related Projects

10,605

Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL).

16,549

A simple PHP API extension for DateTime.

26,791

Faker is a PHP library that generates fake data for you

13,312

Abstraction for local and remote filesystems

A PHP parser written in PHP

29,705

The Symfony PHP framework

Quick Overview

PHPUnit is a widely-used testing framework for PHP. It provides a comprehensive suite of tools for writing, organizing, and running unit tests for PHP applications. PHPUnit is designed to make test-driven development (TDD) in PHP easier and more efficient.

Pros

  • Extensive feature set for various testing scenarios
  • Well-documented with a large community and ecosystem
  • Integrates well with popular IDEs and continuous integration tools
  • Supports both object-oriented and procedural code testing

Cons

  • Steep learning curve for beginners
  • Can be complex to set up and configure for large projects
  • Some features may be overkill for small projects
  • Occasional breaking changes between major versions

Code Examples

  1. Basic test case:
use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase
{
    public function testAddition()
    {
        $calculator = new Calculator();
        $result = $calculator->add(2, 3);
        $this->assertEquals(5, $result);
    }
}
  1. Testing exceptions:
public function testDivisionByZero()
{
    $calculator = new Calculator();
    $this->expectException(DivisionByZeroException::class);
    $calculator->divide(10, 0);
}
  1. Data provider example:
/**
 * @dataProvider additionProvider
 */
public function testAddition($a, $b, $expected)
{
    $calculator = new Calculator();
    $result = $calculator->add($a, $b);
    $this->assertEquals($expected, $result);
}

public function additionProvider()
{
    return [
        [1, 1, 2],
        [0, 5, 5],
        [-1, 1, 0],
    ];
}

Getting Started

  1. Install PHPUnit using Composer:
composer require --dev phpunit/phpunit ^9.5
  1. Create a phpunit.xml configuration file in your project root:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="vendor/autoload.php">
    <testsuites>
        <testsuite name="My Test Suite">
            <directory>tests</directory>
        </testsuite>
    </testsuites>
</phpunit>
  1. Write your tests in the tests directory, following the naming convention *Test.php.

  2. Run your tests using the PHPUnit command:

./vendor/bin/phpunit

Competitor Comparisons

10,605

Mockery is a simple yet flexible PHP mock object framework for use in unit testing with PHPUnit, PHPSpec or any other testing framework. Its core goal is to offer a test double framework with a succinct API capable of clearly defining all possible object operations and interactions using a human readable Domain Specific Language (DSL).

Pros of Mockery

  • More flexible and expressive mocking syntax
  • Better support for partial mocks and spies
  • Easier to mock static methods and global functions

Cons of Mockery

  • Steeper learning curve due to more complex API
  • Slightly slower performance in some scenarios
  • Less integrated with PHPUnit, requiring additional setup

Code Comparison

PHPUnit:

$mock = $this->createMock(SomeClass::class);
$mock->method('someMethod')
     ->willReturn('mocked value');

Mockery:

$mock = Mockery::mock(SomeClass::class);
$mock->shouldReceive('someMethod')
     ->andReturn('mocked value');

Summary

PHPUnit is a comprehensive testing framework that includes built-in mocking capabilities, while Mockery is a dedicated mocking library. PHPUnit offers a simpler, more straightforward approach to mocking, making it easier for beginners. However, Mockery provides more advanced features and flexibility, especially for complex mocking scenarios.

Both libraries are widely used in the PHP ecosystem, and the choice between them often depends on the specific needs of the project and the developer's preferences. Many developers use Mockery in conjunction with PHPUnit for more powerful mocking capabilities while still leveraging PHPUnit's robust testing framework.

16,549

A simple PHP API extension for DateTime.

Pros of Carbon

  • Focused on date and time manipulation, providing a more specialized and comprehensive set of tools for these operations
  • Lightweight and easy to integrate into existing projects
  • Extensive localization support for multiple languages and regions

Cons of Carbon

  • Limited in scope compared to PHPUnit's broader testing capabilities
  • May require additional libraries for more complex date/time operations
  • Less frequent updates and potentially slower bug fixes

Code Comparison

Carbon:

use Carbon\Carbon;

$date = Carbon::now();
echo $date->addWeeks(2)->format('Y-m-d');

PHPUnit:

use PHPUnit\Framework\TestCase;

class MyTest extends TestCase
{
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

Carbon focuses on date and time manipulation, offering a fluent interface for working with dates. PHPUnit, on the other hand, is a testing framework that provides a structure for writing and running unit tests in PHP.

While both libraries serve different purposes, they are essential tools in PHP development. Carbon excels in simplifying date and time operations, making it invaluable for projects dealing with temporal data. PHPUnit, being a testing framework, is crucial for ensuring code quality and reliability across all types of PHP applications.

26,791

Faker is a PHP library that generates fake data for you

Pros of Faker

  • Specialized for generating fake data, making it ideal for seeding databases or creating test data
  • Offers a wide variety of data types and locales, providing more diverse and realistic test data
  • Lightweight and easy to integrate into existing projects

Cons of Faker

  • Limited to data generation, lacking comprehensive testing capabilities
  • Requires manual integration with testing frameworks for full test suite functionality
  • Less actively maintained compared to PHPUnit

Code Comparison

Faker example:

$faker = Faker\Factory::create();
$name = $faker->name;
$email = $faker->email;
$text = $faker->text;

PHPUnit example:

class UserTest extends TestCase
{
    public function testUserCreation()
    {
        $user = new User('John Doe', 'john@example.com');
        $this->assertEquals('John Doe', $user->getName());
        $this->assertEquals('john@example.com', $user->getEmail());
    }
}

Summary

While Faker excels at generating diverse test data, PHPUnit provides a comprehensive testing framework. Faker is best used in conjunction with testing tools like PHPUnit to create more robust and realistic test scenarios. PHPUnit offers a complete suite of testing functionalities but may require additional tools for complex data generation. The choice between the two depends on specific project needs, with many developers opting to use both in tandem for optimal testing workflows.

13,312

Abstraction for local and remote filesystems

Pros of Flysystem

  • Focused on file system abstraction, providing a unified API for various storage systems
  • Lightweight and easy to integrate into existing projects
  • Extensive support for cloud storage providers (e.g., AWS S3, Google Cloud Storage)

Cons of Flysystem

  • Limited to file system operations, unlike PHPUnit's comprehensive testing capabilities
  • Smaller community and fewer contributors compared to PHPUnit
  • Less frequent updates and releases

Code Comparison

PHPUnit (Test Case):

class ExampleTest extends TestCase
{
    public function testExample()
    {
        $this->assertTrue(true);
    }
}

Flysystem (File System Operations):

$filesystem = new Filesystem($adapter);
$contents = $filesystem->read('path/to/file.txt');
$filesystem->write('path/to/newfile.txt', 'contents');

Both projects serve different purposes in the PHP ecosystem. PHPUnit is a comprehensive testing framework, while Flysystem focuses on providing a unified interface for file system operations. PHPUnit has a larger community and more frequent updates, but Flysystem excels in its specific domain of file system abstraction and cloud storage integration.

A PHP parser written in PHP

Pros of PHP-Parser

  • Focused on parsing PHP code, providing a powerful tool for static analysis and code manipulation
  • Offers a more flexible and extensible architecture for working with PHP abstract syntax trees (ASTs)
  • Regularly updated to support the latest PHP language features

Cons of PHP-Parser

  • Narrower scope compared to PHPUnit's comprehensive testing framework
  • Steeper learning curve for developers not familiar with ASTs and code parsing concepts
  • Requires additional integration work to use in testing scenarios

Code Comparison

PHP-Parser example:

$code = '<?php echo "Hello World!";';
$parser = (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
$ast = $parser->parse($code);

PHPUnit example:

class MyTest extends TestCase
{
    public function testHelloWorld()
    {
        $this->assertEquals("Hello World!", helloWorld());
    }
}

While PHP-Parser focuses on parsing and manipulating PHP code, PHPUnit is designed for writing and running unit tests. PHP-Parser is better suited for tasks involving code analysis and transformation, whereas PHPUnit excels in test-driven development and ensuring code correctness through automated testing.

29,705

The Symfony PHP framework

Pros of Symfony

  • Comprehensive full-stack framework for building web applications
  • Modular architecture allowing use of individual components
  • Large ecosystem with extensive documentation and community support

Cons of Symfony

  • Steeper learning curve due to its complexity and size
  • Potentially heavier and slower for smaller projects
  • Requires more configuration and setup compared to PHPUnit

Code Comparison

Symfony (routing example):

use Symfony\Component\Routing\Annotation\Route;

class ProductController extends AbstractController
{
    #[Route('/product/{id}', name: 'product_show')]
    public function show(int $id): Response
    {
        // ...
    }
}

PHPUnit (test example):

use PHPUnit\Framework\TestCase;

class CalculatorTest extends TestCase
{
    public function testAdd(): void
    {
        $calculator = new Calculator();
        $this->assertEquals(4, $calculator->add(2, 2));
    }
}

While Symfony is a full-stack framework for building web applications, PHPUnit is specifically designed for unit testing in PHP. Symfony provides a complete set of tools for web development, including routing, templating, and ORM, whereas PHPUnit focuses solely on testing functionality. The code examples illustrate this difference, with Symfony showing a route definition and PHPUnit demonstrating a simple unit test.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

PHPUnit

Latest Stable Version CI Status codecov

PHPUnit is a programmer-oriented testing framework for PHP. It is an instance of the xUnit architecture for unit testing frameworks.

Installation

We distribute a PHP Archive (PHAR) that has all required (as well as some optional) dependencies of PHPUnit bundled in a single file:

$ wget https://phar.phpunit.de/phpunit-X.Y.phar

$ php phpunit-X.Y.phar --version

Please replace X.Y with the version of PHPUnit you are interested in.

Alternatively, you may use Composer to download and install PHPUnit as well as its dependencies. Please refer to the documentation for details on how to install PHPUnit.

Contribute

Please refer to CONTRIBUTING.md for information on how to contribute to PHPUnit and its related projects.

List of Contributors

Thanks to everyone who has contributed to PHPUnit! You can find a detailed list of contributors on every PHPUnit related package on GitHub. This list shows only the major components:

A very special thanks to everyone who has contributed to the documentation.