greensight / test-factories
Requires
- php: ^8.0
- fakerphp/faker: ^1.10
- illuminate/support: ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.16
- mockery/mockery: ^1.4
- orchestra/testbench: ^6.0
- pestphp/pest: ^1.16
- php-parallel-lint/php-var-dump-check: ^0.5.0
- phpunit/phpunit: ^9.0
This package is auto-updated.
Last update: 2021-10-05 20:41:45 UTC
README
Deprecated, use https://github.com/ensi-platform/php-test-factories instead
Define factories to generate any kind of object or even arrays for unit tests.
Installation
You can install the package via composer:
composer require greensight/test-factories
Basic usage
Let's create a factory and extend abstract Factory.
All you need is to define definition
and make
methods.
use Greensight\TestFactories\Factory; class CustomerFactory extends Factory { public ?int $id = null; public ?FileFactory $avatarFactory = null; public ?array $addressFactories = null; protected function definition(): array { return [ 'id' => $this->whenNotNull($this->id, $this->id), 'user_id' => $this->faker->randomNumber(), 'avatar' => $this->avatarFactory?->make(), 'addresses' => $this->executeNested($this->addressFactories, new FactoryMissingValue()), ]; } public function make(array $extra = []): CustomerDTO { static::$index += 1; return new CustomerDTO($this->mergeDefinitionWithExtra($extra)); } public function withId(?int $id = null): self { return $this->immutableSet('id', $id ?? $this->faker->randomNumber()); } public function withAvatar(FileFactory $factory = null): self { return $this->immutableSet('avatarFactory', $factory ?? FileFactory::new()); } public function includesAddresses(?array $factories = null): self { return $this->immutableSet('addressFactories', $factories ?? [CustomerAddressFactory::new()]); } } // Now we can use Factory like that $customerData1 = CustomerFactory::new()->make(); $customerData2 = CustomerFactory::new()->withId()->withAvatar(FileFactory::new()->someCustomMethod())->make();
As you can see the package uses fakerphp/faker
to generate test data.
You can override any fields in make
method:
$customerData1 = CustomerFactory::new()->make(['user_id' => 2]);
If you target is an array, then you can use a helper method makeArray
:
public function make(array $extra = []): array { return $this->makeArray($extra); }
It's recommended to use $this->immutableSet
in state change methods to make sure previously created factories are not affected.
Making several objects
$customerDataObjects = CustomerFactory::new()->makeSeveral(3); // returns Illuminate\Support\Collection with 3 elements
Contributing
Please see CONTRIBUTING for details.
Testing
- composer install
- npm i
- Start Elasticsearch in your preferred way.
- Copy
phpunit.xml.dist
tophpunit.xml
and set correct env variables there - composer test
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
License
The MIT License (MIT). Please see License File for more information.