zalas/phpunit-doubles

为您初始化PHPUnit测试用例中的测试替身

支持包维护!
jakzal

v1.9.2 2024-01-22 09:53 UTC

README

Build Scrutinizer Code Quality

为您初始化PHPUnit测试用例中的测试替身。

安装

Composer

composer require --dev zalas/phpunit-doubles

Phar

该扩展也作为PHAR分发,可以从最新的Github发行版下载。

将扩展放置在您的PHPUnit扩展目录中。请记住在您的phpunit.xml中指示PHPUnit加载扩展。

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
         extensionsDirectory="tools/phpunit.d"
>
</phpunit>

使用

包含Zalas\PHPUnit\Doubles\TestCase\ProphecyTestDoublesZalas\PHPUnit\Doubles\TestCase\PHPUnitTestDoubles特性,以便在支持的测试替身框架中初始化您的测试替身。

测试替身类型和测试替身框架的类型都来自属性类型

/**
 * @var Vimes|ObjectProphecy
 */
 private $vimes;

目前支持两种测试替身框架

  • Prophecy - Prophecy\Prophecy\ObjectProphecy类型提示
  • PHPUnit - PHPUnit\Framework\MockObject\MockObject类型提示

Prophecy

<?php

use PHPUnit\Framework\TestCase;
use Prophecy\Prophecy\ObjectProphecy;
use Zalas\PHPUnit\Doubles\TestCase\ProphecyTestDoubles;

class DiscworldTest extends TestCase
{
    use ProphecyTestDoubles;

    /**
     * @var Vimes|ObjectProphecy
     */
    private $vimes;

    /**
     * @var Nobby|Fred|ObjectProphecy
     */
    private $nobbyAndFred;

    public function test_it_hires_new_recruits_for_nightwatch()
    {
        $discworld = new Discworld($this->vimes->reveal(), $this->nobbyAndFred->reveal());

        $discworld->createNightWatch();

        $this->vimes->recruit($this->nobbyAndFred)->shouldHaveBeenCalled();
    }
}

PHPUnit

<?php

use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
use Zalas\PHPUnit\Doubles\TestCase\PHPUnitTestDoubles;

class DiscworldTest extends TestCase
{
    use PHPUnitTestDoubles;

    /**
     * @var Vimes|MockObject
     */
    private $vimes;

    /**
     * @var Nobby|MockObject
     */
    private $nobbyAndFred;

    public function test_it_hires_new_recruits_for_nightwatch()
    {
        $discworld = new Discworld($this->vimes, $this->nobby);

        $this->vimes->expects($this->once())
            ->method('recruit')
            ->with($this->nobby);

        $discworld->createNightWatch();
    }
}

贡献

请阅读贡献指南以了解如何为此项目做出贡献。请注意,本项目以贡献者行为准则发布。通过参与本项目,您同意遵守其条款。