chromabits/mockingbird

该包已被废弃,不再维护。未建议替代包。

PHP 模拟工具

v1.0.0 2017-02-23 20:33 UTC

This package is not auto-updated.

Last update: 2024-01-20 23:32:42 UTC


README

PHP 单元测试中模拟依赖的 DSL

特性

  • 像迷你 IoC 容器一样作用于您的单元测试。
  • 自动为您类的依赖创建模拟。
  • 支持通过构造函数和方法注入依赖。
  • 在 Mockery 上提供 DSL 以快速模拟依赖。
  • 您可以提供真实/非模拟实例和标量参数。
  • 与 Laravel 兼容!

要求

  • PHP 7 或更高版本。
  • Composer

安装

在 Composer 项目上运行 composer require chromabits/mockingbird

快速示例

<?php

include_once __DIR__ . '/../vendor/autoload.php';

// Mockingbird is available as a set of functions, which you can import into
// your current scope.
use function Mockingbird\{ stage, on };

// We begin by defining the classes which will act as our dependencies for this
// example.
class DependencyA {
    private $prefix;

    public function __construct(string $prefix)
    {
        $this->prefix = $prefix;
    }

    public function getPrefix(): string { return $this->prefix; }
};
class DependencyB {};
class DependencyC {
    public function sayWorld(string $postfix): string {
        return 'world' . $postfix;
    }
}

// We also define our service class which will consume these dependencies
// through constructor-based and method-based dependency injection.
class Service {
    /**
     * @var DependencyA
     */
    private $a;

    public function __construct(DependencyA $a, DependencyB $b) {
        $this->a = $a;
    }

    public function targetMethod(DependencyC $c): string
    {
        return $this->a->getPrefix() . 'hello ' . $c->sayWorld('!');
    }
};

// Our Service class has three dependencies, two services injected through the
// constructor and one passed on the called method. We will build a stage that
// provides them for us:
//
// - DependencyA: We will pass down a real instance (not a mock).
// - DependencyB: We will let Stage auto-mock it for us.
// - DependencyC: We will manually create our own mock.
//
$result = stage()
    ->provide(new DependencyA('>>> '))
    ->mock(DependencyC::class, [
        on('sayWorld', ['!'], 'worlds!!!'),
    ])
    ->makeAndCall(Service::class, 'targetMethod');

// Should output ">>> hello worlds!!!"
echo $result;