PHPUnit Mock Builder 的灵活 Stub 包装器

4.1.3 2024-02-02 19:21 UTC

This package is auto-updated.

Last update: 2024-08-31 00:32:11 UTC


README

CI Latest Stable Version Total Downloads License

在PHPUnit的Mock Builder之上构建的库,提供了高度简化的语法

参考

  • Stub - 使用静态方法创建 Stub 类
  • Stub 特性 - 使用特性创建 Stub 和 Mock
  • Expected - 为 Mock 定义期望

安装

默认在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