codeception / stub
PHPUnit Mock Builder 的灵活 Stub 包装器
4.1.3
2024-02-02 19:21 UTC
Requires
- php: ^7.4 | ^8.0
- phpunit/phpunit: ^8.4 | ^9.0 | ^10.0 | ^11
Requires (Dev)
- consolidation/robo: ^3.0
Conflicts
- codeception/codeception: <5.0.6
README
在PHPUnit的Mock Builder之上构建的库,提供了高度简化的语法
参考
安装
默认在Codeception中启用。对于PHPUnit,请安装此包
composer require codeception/stub --dev
Stub
可以使用 Codeception\Stub
静态调用来构建 Stub
<?php // create a stub with find method replaced $userRepository = Stub::make(UserRepository::class, ['find' => new User]); $userRepository->find(1); // => User // create a dummy $userRepository = Stub::makeEmpty(UserRepository::class); // create a stub with all methods replaced except one $user = Stub::makeEmptyExcept(User::class, 'validate'); $user->validate($data); // create a stub by calling constructor and replacing a method $user = Stub::construct(User::class, ['name' => 'davert'], ['save' => false]); // create a stub by calling constructor with empty methods $user = Stub::constructEmpty(User::class, ['name' => 'davert']); // create a stub by calling constructor with empty methods $user = Stub::constructEmptyExcept(User::class, 'getName', ['name' => 'davert']); $user->getName(); // => davert $user->setName('jane'); // => this method is empty $user->getName(); // => davert
或者,可以通过使用 Codeception\Test\Feature\Stub
特性 来创建 Stub
<?php $this->make(UserRepositry::class); $this->makeEmpty(UserRepositry::class); $this->construct(UserRepositry::class); $this->constructEmpty(UserRepositry::class); // ...
Mock
应该通过将 Codeception\Test\Feature\Stub
特性 包含在测试用例中来创建 Mock。使用 Codeception\Stub\Expected
设置执行期望
<?php // find should be never called $userRepository = $this->make(UserRepository::class, [ 'find' => Codeception\Stub\Expected::never() ]); // find should be called once and return a new user $userRepository = $this->make(UserRepository::class, [ 'find' => Codeception\Stub\Expected::once(new User) ]);
许可证
MIT