effiana/phpunit-test-generator

为 PHP 类生成 PHPUnit 测试类。

v0.1.1 2020-01-20 08:41 UTC

This package is auto-updated.

Last update: 2024-09-20 18:54:15 UTC


README

这个 PHP 工具可以为您的 PHP 类生成 PHPUnit 测试类。

当前此工具仅支持 PSR4 自动加载策略。如果您希望看到它支持其他自动加载策略和应用组织结构,欢迎提交 pull request。

安装

$ composer require --dev jwage/phpunit-test-generator

您也可以从 发布页面 下载最新的 PHAR。

生成测试类

假设有一个名为 App\Services\MyService 的类,位于 src/Services/MyService.php

namespace App\Services;

class MyService
{
    /** @var Dependency */
    private $dependency;

    /** @var int */
    private $value;

    public function __construct(Dependency $dependency, int $value)
    {
        $this->dependency = $dependency;
        $this->value = $value;
    }

    public function getDependency() : Dependency
    {
        return $this->dependency;
    }

    public function getValue() : int
    {
        return $this->value;
    }
}

并且有一个名为 App\Services\Dependency 的类依赖它,位于 src/Services/Dependency.php

<?php

namespace App\Services;

class Dependency
{
    public function getSomething() : null
    {
        return null;
    }
}

现在您可以使用以下命令为 MyService 生成测试类

$ php vendor/bin/generate-unit-test "App\Services\MyService"

您也可以传递一个类的路径而不是给出类名

$ php vendor/bin/generate-unit-test src/Services/MyService.php

生成的测试类将位于 tests/Services/MyServiceTest.php,如下所示

declare(strict_types=1);

namespace App\Tests\Services;

use App\Services\Dependency;
use App\Services\MyService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;

class MyServiceTest extends TestCase
{
    /** @var Dependency|MockObject */
    private $dependency;

    /** @var int */
    private $value;

    /** @var MyService */
    private $myService;

    public function testGetDependency() : void
    {
        self::assertInstanceOf(Dependency::class, $this->myService->getDependency());
    }

    public function testGetValue() : void
    {
        self::assertSame(1, $this->myService->getValue());
    }

    protected function setUp() : void
    {
        $this->dependency = $this->createMock(Dependency::class);
        $this->value = 1;

        $this->myService = new MyService(
            $this->dependency,
            $this->value
        );
    }
}

现在您有了单元测试的骨架,您可以根据需要填充生成的方法的细节。