hyperia/codecept-unittest-generator

从注释生成单元测试。

1.0.1 2018-01-16 07:15 UTC

This package is not auto-updated.

Last update: 2024-09-12 01:30:06 UTC


README

此软件包允许您从注释中生成PHPUnit测试,这些注释可以写在您的函数文档中。

  • 此软件包的基本用法是生成测试骨架和基本测试。
  • 您必须检查并完成所有生成的测试,包括最基本的函数。
  • 要解析的文件必须声明一个类、抽象类、特质或接口才能被接受。

screenshot_2017-12-08_17-12-32-github

安装

安装此扩展的首选方式是通过 composer

运行以下命令:

composer require hyperia/codecept-unittest-generator:"^1.0"

或者添加以下内容到您的 composer.json 的 require 部分:

"hyperia/codecept-unittest-generator": "^1.0"

配置

在基本配置文件 /codeception.yml 中启用 UnitGenerator 扩展

extensions:
    enabled:
        - Codeception\Extension\RunFailed
    commands:
        - Codeception\Command\UnitGenerator
unitgenerator:
    config: 
        # erase old target files with new one
        overwrite: true 
        # if you want to generate tests for Interface too
        interface: false
        # automaticaly generate tests for getter / setter method
        auto: true
        # ignore errors that can be ignored
        ignore: true
        # regex (/.*config.php/ for example) that files must not match to have a tests generation
        exclude: '/.*Trait.*/'
        # regex (/.*.php/ for example) that files should match to have a tests generation
        include: '/.*.php/'
    dirs:
        # source directory => target directory
        - common/models: tests/unit/unitgen/common/models/
        - console/models: tests/unit/unitgen/console/models/

用法

./vendor/bin/codecept generate:unit

注释

/**
 * @PHPUnitGen\<phpunit_assertion_method>(<expectation>:{<parameters...>}) 
 */

此注释使用一些参数

  • phpunit_assertion_method: 这是您想要使用的PHPUnit断言方法(如 assertEqualsassertInstanceOfassertTrue ...)。

  • expectation: 方法返回的预期值。某些PHPUnit方法不需要它(如 assertTrue),因此在这些情况下,它可以是 null。

  • parameters: 方法参数。

查看以下示例,我们想要自动为该方法生成一些简单测试

<?php
// The class to test content

/** @PHPUnitGen\AssertEquals('expected string':{1, 2, 'a string'}) */
/** @PHPUnitGen\AssertTrue(:{4, 5, 'another'}) */
/** @PHPUnitGen\AssertEquals(null) */
/** @PHPUnitGen\AssertNull() */
public function method(int $arg1 = 0, int $arg2 = 0, string $arg3 = 'default') {}

这些注释将创建基本的PHPUnit测试

<?php
// The generated test for "method" in tests class

$this->assertEquals('expectation string', $this->method(1, 2, 'a string'));
$this->assertTrue($this->method(4, 5, 'another'));
$this->AssertEquals(null, $this->method());
$this->assertNull($this->method());

获取器和设置器注释

<?php
// The class to test content

/** @PHPUnitGen\Get() */
/** @PHPUnitGen\Set() */

这两个注释将允许您自动生成简单获取器/设置器的测试。您的获取器/设置器需要按照以下命名

get<MyProperty>() {}
set<MyProperty>() {}

PHPUnit Generator有一个"自动"选项:如果您激活它,它将在找到以"get"或"set"开头的方法时搜索属性,如果属性存在,它将生成测试。

私有或受保护的方法

如果要测试的方法是私有或受保护的,PHPUnit Generator将使用PHP ReflectionClass访问该方法。

要求

UnitGenerator运行需要以下组件

  • Codeception UnitGenerator是Codeception的模块。它需要一个运行的此工具版本。
  • Phpunit-generator 软件包。