wojciech.nawalaniec / mother-object-factory
使创建母对象变得非常简单的库。
Requires
- php: ^8.1
- fakerphp/faker: ^1.22
- mouf/classname-mapper: ^1.0
- nette/php-generator: ^4.0
- symfony/cache: ^6.3
- symfony/console: ^6.2
- thecodingmachine/class-explorer: ^1.1
Requires (Dev)
- infection/infection: ^0.27.0
- phpunit/phpunit: ^10.1
This package is auto-updated.
Last update: 2024-02-23 23:37:32 UTC
README
母对象工厂
我创建了这个库,因为我喜欢在我的测试代码中创建母对象。我注意到其中大部分都是一堆可以轻松生成的样板代码。
母对象是一个用于测试目的的测试类,用于创建示例对象,有助于简化测试设置并在多个测试中重用固定值。更多内容请参阅上面的链接。
安装
composer require --dev wojciech.nawalaniec/mother-object-factory
示例
假设我们的代码中有一个这样的类,我们在测试中经常使用它
final class User { public function __construct(string $name) { $this->name = $name; } public function name(): string { return $this->name; } private string $name; }
这是一个非常简单的类,创建这个类的新实例就像这样简单
$obj = new User('John Wick');
尽管创建对象很简单,但仍然不是最好的主意,让几十个地方负责创建 User
对象,因为当这个类的构造函数发生变化时,许多测试都将受到影响。但避免在每个测试中创建 User
对象的新实例的更好原因在于,想象这样的类
class Post { public static function create(Title $title, Content $content, User $author): void { // ... } }
对于这样的类,我们可能有很多测试,因为有3个参数。并不是每个测试中每个参数的值对我们来说都是特别重要的。有些测试将更多地关注 $title
参数,有些测试将更多地关注 $content
和 $author
。创建每个对象的新实例可能会模糊特定测试用例的目标。
因此,当我想在 $title
参数的上下文中测试这个 create
方法时,我希望能够编写一个测试用例,其中 $title
参数是主角,它吸引了读者99%的注意力。我想清楚地说明测试的内容。
public function testCreatingPost_TitleIsTooLong_ThrowsException(): void { $tooLongTitle = TitleMother::newObject() ->ofLength(Title::MAX_LENGHT+1) ->create(); Post::create($tooLongTitle, ContentMother::any(), UserMother::any()); }
用法
要生成母对象,只需输入
./vendor/bin/motherObjectFactory generate App\\Package\\Class
将 App\\Package\\Class
更改为你的代码中的任何类。然后你将被要求提供一个命名空间,其中将创建母对象。你可以使用基于你的 composer.json
文件的自动完成功能,输入前几个字母并使用 TAB
键。完成后,按 enter
键,将创建新的填充。如有必要,请修改它。