Skip to content
Skills Library
Programming · Testing

phpunit

/phpunit

Expert PHPUnit testing assistance covering PHP assertions, data providers, and test doubles. Use when writing unit and functional tests for PHP, Laravel, Symfony, or WordPress.

Licence
MIT
Last repository change
01.10.2026

Assessment and security

100/ 100Class: good
Format25 / 25
Frontmatter with name and description, valid name, description up to 1,024 characters, name matching the folder.
Discoverability25 / 25
Description explains when to use the skill, has a reasonable length and uses third person.
Content35 / 35
At least 150 words and at most 500 lines, headings, step lists, examples or code.
Hygiene15 / 15
No placeholders such as TODO, no Windows paths, with a licence.
Riskno signals detected in the scan
Files in this package
1
Scripts
0
HTML comments
0
URLs in SKILL.md
2
Deprecation

No signals detected. Repository changed on 01.10.2026, without references to retired models or APIs.

Licence

MIT, open: use and modify while retaining author attribution.

What it does and when to use it

Expert PHPUnit testing assistance covering PHP assertions, data providers, and test doubles. Use when writing unit and functional tests for PHP, Laravel, Symfony, or WordPress.

Original author description

Expert PHPUnit testing assistance covering PHP assertions, data providers, and test doubles. Use when writing unit and functional tests for PHP, Laravel, Symfony, or WordPress.

How it works

  1. When to Use
  2. Quick Start
  3. Core Concepts
  4. Common Patterns
  5. Best Practices
  6. Troubleshooting
  7. References
Original SKILL.md headings · 166 lines, 524 words
SKILL.md preview
---
name: phpunit
description: Expert PHPUnit testing assistance covering PHP assertions, data providers, and test doubles. Use when writing unit and functional tests for PHP, Laravel, Symfony, or WordPress.
---

# PHPUnit

PHPUnit is the standard unit testing framework for the PHP ecosystem. Examples include usage in Laravel, Symfony, and WordPress.

## When to Use

- **PHP Standard Testing Framework**: The official, universal testing framework for Laravel, Symfony, and modern PHP applications.
- **Unit and Integration Testing**: Testing PHP domain models, services, controllers, and database interactions.
- **Data Providers for Parameterized Tests**: Running tests against multi-dimensional test datasets using `@dataProvider`.
- **Mocking & Test Doubles**: Generating mock objects and verifying invocation expectations natively without external libraries.

## Quick Start

```php
<?php
use PHPUnit\Framework\TestCase;

final class StackTest extends TestCase
{
    public function testPushAndPop(): void
    {
        $stack = [];
        $this->assertEmpty($stack);

        array_push($stack, 'foo');
        $this->assertNotEmpty($stack);
        $this->assertEquals('foo', array_pop($stack));
    }
}
```

## Core Concepts

### PHPUnit Test Case Structure

Extends `TestCase` and leverages modern PHP 8 attributes:

```php
<?php
use PHPUnit\Framework\TestCase;
use PHPUnit\Framework\Attributes\Test;
use PHPUnit\Framework\Attributes\DataProvider;

final class CurrencyConverterTest extends TestCase
{
    #[Test]
    #[DataProvider('currencyProvider')]
    public function it_converts_usd_to_eur(float $usd, float $expectedEur): void
    {
        $converter = new CurrencyConverter(exchangeRate: 0.92);
        $this->assertEqualsWithDelta($expectedEur, $converter->toEur($usd), 0.01);
    }

    public static function currencyProvider(): array
    {
        return [
            'zero value' => [0.0, 0.0],
            'standard transaction' => [100.0, 92.0],
            'fractional amount' => [10.50, 9.66],
        ];
    }
}
```

### Native Mock Objects

Stubs methods and asserts on invocation parameters:

```php
public function testPaymentServiceSendsNotification(): void
{
    $mailerMock = $this->createMock(MailerInterface::class);
    $mailerMock->expects($this->once())
        ->method('send')
        ->with($this->equalTo('user@example.com'));

    $service = new PaymentService($mailerMock);
    $service->processPayment('user@example.com', 50);
}
```

### Declarative phpunit.xml Configuration

Configures test suites, environment variables, and coverage enforcement:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         bootstrap="vendor/autoload.php"
         colors="true"
         cacheDirectory=".phpunit.cache">
    <testsuites>
        <testsuite name="Unit">
            <directory>tests/Unit</directory>
        </testsuite>
    </testsuites>
    <source>
        <include><directory>src</directory></include>
    </source>
</phpunit>
```

## Common Patterns

### Data Providers for Clean Test Matrices

**Problem**: Writing multiple separate test methods to validate email formatting regex rules.

**Solution**:
Use PHPUnit Data Providers:

```php
use PHPUnit\Framework\TestCase;

class ValidatorTest extends TestCase
{
    /**
     * @dataProvider emailProvider
     */
    public function testEmailValidation(string $email, bool $expected): void
    {
        $validator = new EmailValidator();
        $this->assertSame($expected, $validator->isValid($email));
    }

    public static function emailProvider(): array
    {
        return [
            ['test@example.com', true],
            ['invalid-email', false],
            ['user@sub.domain.org', true],
            ['', false],
        ];
    }
}
```

## Best Practices

**Do**:

- Adopt PHP 8 Attributes: Use `#[Test]` and `#[DataProvider]` instead of legacy docblock annotations (`@test`).
- Use Static Data Providers: Ensure all data provider methods are declared as `public static`.
- Run with `--colors=always --testdox`: Produce clean, human-readable test output in local terminals and CI.
- Enforce Strict Types in Tests: Add `declare(strict_types=1);` at the top of all test files.

**Don't**:

- Use `@runInSeparateProcess` unless strictly necessary: Process isolation adds severe performance overhead.
- Use `assertEquals` on floats: Use `assertEqualsWithDelta` to avoid floating point precision failures.
- Catch exceptions manually: Use `$this->expectException(CustomException::class)` to assert on thrown errors.

## Troubleshooting

| Error                                                  | Cause                                                            | Solution                                                                 |
| :----------------------------------------------------- | :--------------------------------------------------------------- | :----------------------------------------------------------------------- |
| `Class 'PHPUnit\Framework\TestCase' not found`         | Composer autoload missing or PHPUnit not installed via Composer. | Run `composer dump-autoload` and execute via `./vendor/bin/phpunit`.     |
| `Failed asserting that false is true`                  | Method assertion failed.                                         | Add custom failure message: `$this->assertTrue($val, 'Custom message')`. |
| `Risky Test: This test did not perform any assertions` | Test executed code without performing explicit `$this->assert*`. | Add assertion or mark with `@doesNotPerformAssertions` annotation.       |

## References

- [PHPUnit Documentation](https://phpunit.de/documentation.html)

Versions

RepositoryScoreLicence
This page · G1Joshi/Agent-Skills100MIT
xobotyi/cc-foundry100MIT

Database snapshot: 13.11.2026 · package version 932b34a7b2a9 (SHA-256 digest of the entire package)

Downloads in the last 30 days: 0 · ranking

Report a problem with this skill: harmful content, incorrect descriptions or an author’s removal request.

Similar skills

  • 100php-testing
    Write PHP tests with PHPUnit — unit tests, mocking, data providers, assertions, test doubles, and TDD workflow. Use when writing tests for WooCommerce extensions or PHP projects.
  • 100php-testing
    Write PHP tests with PHPUnit — unit tests, mocking, data providers, test doubles, assertions, and TDD practices. Use when writing tests for PHP code, whether in Magento or standalone PHP applications.
  • 95phpunit-skill
    Generates PHPUnit tests in PHP. Covers assertions, data providers, mocking, and test doubles. Use when user mentions "PHPUnit", "TestCase", "assertEquals", "PHP test". Triggers on: "PHPUnit", "TestCase PHP", "assertEquals PHP", "PHP unit test".
  • 100php-testing
    Write unit and integration tests for PHP applications with PHPUnit and Pest. Use when writing PHPUnit unit tests or integration tests for PHP applications.
  • 100php-testing
    Use when writing/configuring tests on a non-Laravel PHP project — PHPUnit vs Pest. Do NOT use for Laravel test helpers or quality tooling (php-quality-tooling).
  • 90php-testing-patterns
    Use when writing or reviewing PHP tests - PHPUnit assertions, WordPress test utilities (WP_UnitTestCase, factories), WooCommerce test patterns, and Brain Monkey isolation.

Feedback and reports

Your message goes to Bartosz Sokoliński. An email address is needed only for a reply. See the privacy policy.