Nico
Nico

Reputation: 459

PHPUnit configure extension to run for a specific test suite

I want to run a PHPUnit test runner 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!

Upvotes: 1

Views: 1187

Answers (1)

hakre
hakre

Reputation: 198199

Well, there is a reason to have a configuration file.

Or two. (Or three and so on).

Honestly, the most straight forward way is to invoke the test-runner with the appropriate configuration file and then you can have all the variants you're looking for.

Introduce a Makefile or composer scripts so you have some book-keeping on how you invoke the different configurations and have them at your fingertips.

If you want to extend, Phpunit is pure php and you could fiddle with superglobals and your own bootstrapping - perhaps on runner extension level - but this is not making anything more easy nor portable or your tests any better (very most likely, no offence please).

Upvotes: 2

Related Questions