schranz / test-generator
一个用于生成单元测试的命令行工具。
0.4.6
2024-01-11 18:35 UTC
Requires
- php: ^8.1
- nikic/php-parser: ^4.18 || ^5.0
- symfony/filesystem: ^5.4 || ^6.0 || ^7.0
- symfony/process: ^5.4 || ^6.0 || ^7.0
- symfony/string: ^5.4 || ^6.0 || ^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.6
- phpstan/phpstan: ^1.4
- phpstan/phpstan-phpunit: ^1.0
- phpstan/phpstan-webmozart-assert: ^1.0
- phpunit/phpunit: ^10.4
- rector/rector: ^0.19
- symfony/finder: ^5.4 || ^6.0 || ^7.0
- symfony/var-dumper: ^5.4 || ^6.0 || ^7.0
- thecodingmachine/phpstan-strict-rules: ^1.0
README
本项目利用 PHPStan(WIP)和 PHPParser,通过解析给定PHP文件的 AST 来生成测试用例。
为什么?
使用静态代码分析器可以生成大多数被遗忘的测试。项目的目标不是生成完整的测试用例,而是应该生成测试用例中的最大量模板代码,并告诉类方法应该实现哪些方法。
所以,如果有一个如下所示的方法
public function setTitle(?string $title): void { $this->title = $title; } public function getTitle(): void { $this->title = $title; }
如果你使用代码覆盖率,当你进行测试时你会得到100%
public function testSetTitle(): void { $model = $this->createInstance(); $model->setTitle('Test'); $this->assertSame('Test', $model->getTitle()); }
但是,由于 ?string
可以看作是 string|null
的联合类型,所以缺少了 null
类型的测试用例。
public function testSetTitleNull(): void { $model = $this->createInstance(); $model->setTitle(null); $this->assertNull($model->getTitle()); }
本项目目标是预先生成该测试用例的模板代码。
安装
composer require --dev schranz/test-generator
配置
创建一个名为 tests/generator-config.php
的新文件
<?php use Schranz\TestGenerator\Domain\Model\Config; $config = new Config(); // add following hooks if you want to use `rector` or `php-cs-fixer` directly on the created test files // $config->hooks[] = 'vendor/bin/rector process %s'; // $config->hooks[] = 'vendor/bin/php-cs-fixer fix %s'; return $config;
有关所有选项,请参阅 Config.php。
建议在项目的 phpunit.xml
中也将 failOnIncomplete
配置为 true
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd" ... + failOnIncomplete="true" >
这样生成的测试会自动失败,并需要开发者的调整和审查。
使用
vendor/bin/test-generator src/YourNameSpace/YourFile.php