icanhazstring/phpunit-faker-extension

PHPUnit extension to add faker support

0.1 2019-01-25 14:32 UTC

This package is auto-updated.

Last update: 2024-03-26 03:38:07 UTC


README

Build Min php version Min phpunit version

Using this extension you can use fzaninotto/faker with your phpunit tests. Every test will be seeded so you will be able run the same test again if an error occurs.

phpunit-faker-extension-screenshot

Installation

You can install this extension by using Composer. This package should be added as a require-dev dependency:

composer require --dev icanhazstring/phpunit-faker-extension

Usage

Enable with all defaults by adding the following code to your project's phpunit.xml file:

<phpunit bootstrap="vendor/autoload.php">
...
    <listeners>
        <listener class="PHPUnitFaker\FakerTestListener" />
    </listeners>
</phpunit>

Now run the test suite as normal. As soon as all tests are completed, you will see a seed that was used to generate the faker data:

Tests done with seed: XXX

Using Fake inside a test

To use faker inside your tests, you will need to implement the FakerAwareTest interface and the FakerTrait. Since not all tests will need faker, the interface makes sure only tests using faker, will get the needed data.

To actually invoke you only need to do the following:

class AwesomeTest extends TestCase implements FakerAwareTest
{
    use FakerTrait;
    
    public function testAwesomeStuff(): void
    {
        $this->assertSame($this->fake()->name, $this->fake()->name);
    }
}

See faker documentation for more information about formatters: https://github.com/fzaninotto/faker#formatters

Running tests with a given seed

To run tests with a given seed, simple set the PHPUNIT_SEED environment variable before running phpunit:

$ PHPUNIT_SEED=XXX vendor/bin/phpunit

Configuration

This extension has three configurable parameters:

  • locale - The locale that faker should use (Default: en_GB)
  • fakerProviderProvider - (Silly name I know) A single invokable class returning a list of providers (string or instance)

These configuration parameters are set in phpunit.xml when adding the listener:

<phpunit bootstrap="vendor/autoload.php">
    <!-- ... other suite configuration here ... -->

    <listeners>
        <listener class="PHPUnitFaker\FakerTestListener">
            <arguments>
                <array>
                    <element key="locale">
                        <string>de_DE</string>
                    </element>
                    <element key="fakerProviderProvider">
                        <string>Your\FakerProviderProvider</string>
                    </element>
                </array>
            </arguments>
        </listener>
    </listeners>
</phpunit>

License

phpunit-faker-extension is available under the MIT License.