ekiwok/quick-fixtures

基于 @var 注解生成复杂的测试用例。

0.9.1 2017-01-16 23:55 UTC

This package is auto-updated.

Last update: 2024-09-14 10:14:08 UTC


README

  • 你是否曾因为不想在测试用例中使用反射而添加了不必要的setter方法?
  • 你是否因为用这种方式编写测试用例太混乱而放弃了使用值对象?
  • 你是否创建了特质来帮助在测试用例中创建 \DateTime?

如果你上述任何一个问题,你可能觉得这个工具会很有帮助。

这个小巧的库可以根据你在代码中已经存在的 dockblock 注解快速生成测试用例。

提供的生成器接受关联数组,因此你可以将测试用例数据保存在你选择的文件中。这可能是一个 yaml、xml、csv 等文件...

例如,准备一个yaml文件如下

    "Jake Weary":
        uuid: "123e4567-e89b-12d3-a456-426655440000"
        name: "Jake Weary"
        email: "jake.weary@example.com"
        # Notice that for single property objects it's ok to skip property name
        credit: 100

然后使用这些数据来生成测试用例

    $jakeWearyData = /* fetch "Jake Weary" entry from yml */

    $jakeWeary = $generator->generate(Customer::class, $jakeWearyData);

而不是编写

    $jakeWeary = new Customer(
        '123e4567-e89b-12d3-a456-426655440000',
        'Jake Weary',
        'jake.weary@example.com',
        new Credit(100),
    );

或者

    $jakeWeary = (new Customer())
        ->setUUID('123e4567-e89b-12d3-a456-426655440000')
        ->setName('Jake Weary')
        ->setEmail'jake.weary@example.com')
        ->setCredit(new Credit(100))
    ;

安装

使用composer安装: composer require ekiwok/quick-fixtures

扩展

它很容易通过添加自己的处理器进行扩展。

    $generator->addProcessor(new class implements \Ekiwok\QuickFixtures\Processor\PrioritisedProcessorInterface{
    
        public function getPriority()
        {
            return 1025;
        }
    
        public function process(\Ekiwok\QuickFixtures\ContextInterface $context, $payload, \Ekiwok\QuickFixtures\GeneratorInterface $generator)
        {
            return new \DateTime($payload);
        }
    
        public function applies(\Ekiwok\QuickFixtures\ContextInterface $context, $payload)
        {
            $type = $context->getType();
            
            // in real life we would also check payload to be sure it
            // also makes sense
    
            return $type->hasAnyClass()
                && $type->hasClass(\DateTime::class);
        }
    });

具有此优先级的处理器将在内置处理器之前运行,并将设置所有标记为 @var \DateTime 的属性。

文档