greensight/test-factories

该包已被弃用且不再维护。作者建议使用ensi/test-factories包。

0.1.0 2021-08-23 14:08 UTC

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

基本用法

让我们创建一个工厂并扩展抽象工厂。您只需要定义 definitionmake 方法。

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

测试

  1. composer install
  2. npm i
  3. 以您喜欢的任何方式启动Elasticsearch。
  4. phpunit.xml.dist 复制到 phpunit.xml 并在正确设置环境变量
  5. composer test

安全漏洞

请查看我们如何报告安全漏洞的 安全策略

许可

MIT许可证(MIT)。有关更多信息,请参阅许可文件