'PHPUnit configure extension to run for a specific test suite

I want to run a PHPUnit extension for a specific test suite only, but I did not find a way to achieve that.

I know that extensions can be configured using arguments, however, it seems to be no way to retrieve the current test suite. We can also take a broader view and may want to retrieve the options passed to the PHPUnit command-line test runner.

My phpunit.xml file is configured as following (simplified for the example purpose):

    <phpunit>
        <testsuites>
            <testsuite name="unit">
                <directory>ci/unit</directory>
            </testsuite>
            <testsuite name="unit-with-extension">
                <directory>ci/unit-with-extension</directory>
            </testsuite>
        </testsuites>
        <extensions>
            <extension class="Extensions\CustomExtension"/>
        </extensions>
    </phpunit>

The custom extension:

declare(strict_types=1);

namespace Extensions\CustomExtension;

use PHPUnit\Runner\AfterLastTestHook;
use PHPUnit\Runner\BeforeFirstTestHook;

class CustomExtension implements AfterLastTestHook, BeforeFirstTestHook
{
    public function executeBeforeFirstTest(): void
    {
        ...
    }

    public function executeAfterLastTest(): void
    {
        ...
    }
}

Finally, the test suite is run using:

phpunit --unit-with-extension

Thank you for your assistance!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source