greensight / test-factories
该包已被弃用且不再维护。作者建议使用ensi/test-factories包。
0.1.0
2021-08-23 14:08 UTC
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
已弃用,请使用 https://github.com/ensi-platform/php-test-factories 替代
定义工厂以生成任何类型的对象或甚至为单元测试生成数组。
安装
您可以通过composer安装此包
composer require greensight/test-factories
基本用法
让我们创建一个工厂并扩展抽象工厂。您只需要定义 definition
和 make
方法。
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();
如您所见,该包使用 fakerphp/faker
生成测试数据。
您可以在 make
方法中覆盖任何字段
$customerData1 = CustomerFactory::new()->make(['user_id' => 2]);
如果目标是数组,则可以使用辅助方法 makeArray
public function make(array $extra = []): array { return $this->makeArray($extra); }
建议在状态更改方法中使用 $this->immutableSet
,以确保先前创建的工厂不受影响。
生成多个对象
$customerDataObjects = CustomerFactory::new()->makeSeveral(3); // returns Illuminate\Support\Collection with 3 elements
贡献
有关详细信息,请参阅 CONTRIBUTING
测试
- composer install
- npm i
- 以您喜欢的任何方式启动Elasticsearch。
- 将
phpunit.xml.dist
复制到phpunit.xml
并在正确设置环境变量 - composer test
安全漏洞
请查看我们如何报告安全漏洞的 安全策略
许可
MIT许可证(MIT)。有关更多信息,请参阅许可文件