jainec/hyperf-fakie

Hyperf PHP 的测试对象工厂

v0.1.7 2023-12-12 22:04 UTC

This package is auto-updated.

Last update: 2024-09-13 00:12:15 UTC


README

这个 PHP Hyperf 库旨在帮助您生成用于测试目的的完全填充了虚假/随机数据的对象。

Latest Stable Version Total Downloads License PHP Version Require

安装

composer require jainec/hyperf-fakie

配置

发布配置文件,以便您可以定义自己的规则

php bin/hyperf.php vendor:publish jainec/hyperf-fakie

配置文件将显示在以下路径

config/autoload/fakie.php

在此文件中,您可以定义特定类和属性的创建规则

<?php

declare(strict_types=1);

return [
    'rules' => [
        'App\Entity\User' => [
            'type' => array_rand(['CONSUMER', 'SELLER']),
        ],
        'App\Entity\Order' => [
            'type' => array_rand(['VIRTUAL', 'PHYSICAL']),
        ],
        'Class' => [
            'property1' => 'rule1',
            'property2' => 'rule2',
        ],
    ],
];

用法

简单用法

没有 hyperf-fakie

// Ex.: Generating an OrderHistory object for testing purposes
$order = new Order(
    id: rand(),
    type: array_rand(['VIRTUAL', 'PHYSICAL']),
    amount: rand(),
    value: rand() / 100,
);

$user = new User(
    name: Str::random(),
    telephone: Str::random(),
    city: Str::random(),
);

$order_history = new OrderHistory(
    id: rand(),
    description: Str::random(),
    order: $order,
    user: $user,
);

看看 hyperf-Fakie 是多么简单

// Ex.: Generating an OrderHistory object for testing purposes with fakie
$order_history = Fakie::object(OrderHistory::class)->create();

覆盖属性值

$user = Fakie::object(OrderHistory::class)->create([
    'description' => 'Specific description for specific test case'
]);

使用除了 __construct() 之外的方法构建对象

您只能使用此功能,如果您的对象可以使用接受具有 [properties => values] 作为参数的数组的 接受数组 的方法来构建

$user = Fakie::object(UserDTO::class, 'fromArray')->create();

在这种情况下,Fakie 将创建并分配随机值给类的所有属性。如果您的属性方法不需要接收,您可以使用 excludeProperties 删除它们

$user = Fakie::object(UserDTO::class, 'fromArray')->excludeProperties(['type', 'age'])->create();

在上面的示例中,属性 typeage 将不会使用,也不会传递给 fromArray 方法

重要

  • Fakie 使用类的属性类型来生成和分配随机值
  • 如果属性没有定义类型,将分配默认的 string
  • 如果属性类型是 arrayarray<Type>,建议您在配置 fakie.php 文件中定义自己的规则。因为我们知道在 PHP 中,我们无法确定数组内部期望的内容
  • 如果属性类型是抽象/接口,您 需要 为这些情况指定自己的规则,指定一个具体的类
  • 您还可以使用 Fakie 对象在您的配置文件中指定规则
<?php

declare(strict_types=1);

return [
    'rules' => [
        'App\Entity\OrderHistory' => [
            'order' => Fakie::object(Order::class), // Don't call the create() method here
            'user' => Fakie::object(User::class, 'fromArray'), // Don't call the create() method here
        ],
    ],
];

请随时贡献!帮助我们改进Fakie!🎉

MIT © 2022 Jaine Conceição Santos