jwage / phpunit-test-generator

为PHP类生成PHPUnit测试类。

0.0.3 2018-12-14 03:29 UTC

This package is auto-updated.

Last update: 2024-09-18 10:08:16 UTC


README

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

该工具目前仅支持PSR4自动加载策略。如果您希望看到它支持其他自动加载策略和应用程序组织结构,欢迎提交拉取请求。

安装

$ 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
        );
    }
}

现在您有了测试类的框架,您可以填写生成的方法的详细信息。