PHPackages                             proklung/phpunit-testing-tools - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. proklung/phpunit-testing-tools

ActiveLibrary[Testing &amp; Quality](/categories/testing)

proklung/phpunit-testing-tools
==============================

PHPUNIT testing tools.

1.5.8(3y ago)332820MITPHP

Since Apr 22Pushed 3y ago1 watchersCompare

[ Source](https://github.com/ProklUng/phpunit.testing.tools)[ Packagist](https://packagist.org/packages/proklung/phpunit-testing-tools)[ RSS](/packages/proklung-phpunit-testing-tools/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (10)Dependencies (36)Versions (59)Used By (20)

Кастомные инструменты для PHPUnit тестов
========================================

[](#кастомные-инструменты-для-phpunit-тестов)

**INTERNAL**

Установка
---------

[](#установка)

`composer require --dev proklung/phpunit-testing-tools`

Всякое
------

[](#всякое)

### Как построить тестовый контейнер

[](#как-построить-тестовый-контейнер)

Создать класс:

```
use Prokl\TestingTools\Base\BaseTestCase;
use Prokl\TestingTools\Tools\Container\BuildContainer;

class ContainerAwareBaseTestCase extends BaseTestCase
{
    /**
     * @inheritDoc
     * @throws Exception
     */
    protected function setUp(): void
    {
        $this->container = static::$testContainer = BuildContainer::getTestContainer(
            [
                'dev/test_container.yaml',
                'dev/local.yaml'
            ],
            '/Resources/config',
            [new SampleCompilerPass()], // Опциональный параметр - кастомные compiler passes,
            'dev', // Окружение. По умолчанию - dev
            true   // Debug. По умолчанию - true,
            ['service_to_mock'] // Сервисы, подлежащие мокингу (см. подраздел Моки сервисов)
        );

        parent::setUp();
    }
}
```

Отнаследовать от него тест.

Подгрузятся конфиги сервисов из указанных файлов по указанному пути (относительно DOCUMENT\_ROOT тестов).

### Мокинг сервисов для функциональных тестов

[](#мокинг-сервисов-для-функциональных-тестов)

Механизм (на базе создания прокси-сервисов по заданному списку) взят из [бандла](https://github.com/Happyr/service-mocking)и адаптирован под локальные нужды.

```
use Prokl\TestingTools\Tools\ServiceMocker;
use Prokl\TestingTools\Base\BaseTestCase;

class MyTest extends BaseTestCase
{
    use RestoreServiceContainer;

        protected function setUp(): void
        {
            parent::setUp();

            $this->container = BuildContainer::getTestContainer(
                [
                    'test_container.yaml'
                ],
                '/../../../../tests/Standalone/Resource/config',
                [],
                'dev',
                true,
                ['filesystem.local.adapter'] // Сервис, который будет заменен моком.
            );
    }

    public function testFoo()
    {
        // For all calls
         ServiceMock::all($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
             return new Local(
                 $_SERVER['DOCUMENT_ROOT'] .  '/test/');
         });

         $result = $this->container->get('filesystem.local.adapter');

        // For only the next call
         ServiceMock::next($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
             return new Local(
                 $_SERVER['DOCUMENT_ROOT'] .  '/test/');
         });

        // This will queue a new callable
         ServiceMock::next($this->container->get('filesystem.local.adapter'), 'getAdapter', function () {
             throw new \InvalidArgument('getAdapter can call once time!');
         });

        $mock = // create a PHPUnit mock or any other mock you want.
        ServiceMocker::swap($this->container->get('filesystem.local.adapter'), $mock);

        // ...

         $service = $this->container->get('filesystem.local.adapter');
         $result = $service->getAdapter(); // Метод сервиса (или сервис целиком) подменен.
    }

    protected function tearDown(): void
    {
        // To make sure we don't affect other tests
        ServiceMock::resetAll();
        // You can include the RestoreServiceContainer trait to automatically reset services
    }
}
```

BootTestKernelTrait
-------------------

[](#boottestkerneltrait)

```
use Prokl\TestingTools\Traits\BootTestKernelTrait;

class ExampleTest extends \Prokl\TestingTools\Base\BaseTestCase
{
    use BootTestKernelTrait;

    protected function setUp(): void
    {
        parent::setUp();

        $container = new ContainerBuilder();

        // ... Наполнение тестового контейнера.

        self::$kernel = $this->bootTestKernel($container);
    }
}
```

CommandTestCase
---------------

[](#commandtestcase)

Базовый класс для тестирования консольных команд.

Методы:

- `executeCommand(Command $commandInstance, string $commandName, array $params = [])` - вернет то, что команда вывела на экран.
- `runCommand(Command $command, $input = [])` - вернет результат выполнения метода `execute` команды.

Трэйт DefaultDataProviders
--------------------------

[](#трэйт-defaultdataproviders)

Несколько общих дата-провайдеров

- `provideEmptyValue` - пустые значения.
- `provideEmptyScalarValue` - пустые скалярные значения
- `provideBooleanValue` - булевы значения
- `provideDateTimeInstance` - инстанц DateTime
- `provideNotExistingFilePath` - путь к несуществующему файлу

Мокер функций
-------------

[](#мокер-функций)

Обертка [над](https://github.com/php-mock/php-mock-mockery).

Пример (в тесте, унаследованном от `BaseTestCase`):

```
        // Замокается полностью (т.е. не важно с какими параметрами пройдет вызов) функция in_the_loop
        $this->mockerFunctions->setNamespace('\Tests\API')
            ->full('in_the_loop', true)
            ->mock();
```

`Namespace` - пространство имен, в котором мокается функция.

Или частичное моканье (в зависимости от аргументов):

```
       // При вызове  get_cat_name с аргументом $this->idCategory вернет Mocked category
       $this->mockerFunctions->setNamespace('Test\API\Entity')
            ->partial('get_cat_name', 'Mocked category', $this->idCategory)
            ->partial('category_description', 'Mocked category description', $this->idCategory)
            ->mock();
```

При использовании этой фичи рекомендуется (во избежании проблем) на тест ставить аннотации:

```
    /**
     * data()
     *
     * @runInSeparateProcess
     * @preserveGlobalState disabled
     */
```

Трэйт ServiceLocatorConstructorTrait
------------------------------------

[](#трэйт-servicelocatorconstructortrait)

Конструктор сервис-локаторов Symfony для тестов.

Метод:

- `constructServiceLocator(array $config)` - где `$config` массив вида:

```
$object = new ClassName();

$config = [
 'service_key' => ClassName::class,
 'service_key2' => $object,

];
```

Если передать название класса в конфиге, то внутри метода класс будет инстанцирован.

Console test
------------

[](#console-test)

Форк [пакета](https://github.com/kbond/console-test)

```
use App\Command\CreateUserCommand;
use Prokl\TestingTools\Base\BaseTestCase;
use Prokl\TestingTools\Tools\Console\InteractsWithConsole;
use Prokl\TestingTools\Traits\BootTestKernelTrait;

class CreateUserCommandTest extends BaseTestCase
{
    use InteractsWithConsole;
    use BootTestKernelTrait;

    protected function setUp(): void
    {
        parent::setUp();

        $container = new ContainerBuilder();

        $container->setDefinition(
            IntegrityCheck::class,
            new Definition(IntegrityCheck::class, [])
        )->setTags(['console.command' => ['command' => 'module:еуые']])->setPublic(true);

        self::$kernel = $this->bootTestKernel($container);

        $this->cliApplication = new \Symfony\Bundle\FrameworkBundle\Console\Application(self::$kernel);
        $this->cliApplication->add($container->get(IntegrityCheck::class));
    }

    public function test_can_create_user(): void
    {
        $this->executeConsoleCommand('create:user kbond --admin --role=ROLE_EMPLOYEE --role=ROLE_MANAGER')
            ->assertSuccessful() // command exit code is 0
            ->assertOutputContains('Creating admin user "kbond"')
            ->assertOutputContains('with roles: ROLE_EMPLOYEE, ROLE_MANAGER')
            ->assertOutputNotContains('regular user')
        ;

        // advanced usage
        $this->consoleCommand(CreateUserCommand::class) // can use the command class or "name"
            ->splitOutputStreams() // by default stdout/stderr are combined, this options splits them
            ->addArgument('kbond')
            ->addOption('--admin') // with or without "--" prefix
            ->addOption('role', ['ROLE_EMPLOYEE', 'ROLE_MANAGER'])
            ->addOption('-R') // shortcut options require the "-" prefix
            ->addOption('-vv') // by default, output has normal verbosity, use the standard options to change (-q, -v, -vv, -vvv)
            ->addOption('--ansi') // by default, output is undecorated, use this option to decorate
            ->execute() // run the command
            ->assertSuccessful()
            ->assertStatusCode(0) // equivalent to ->assertSuccessful()
            ->assertOutputContains('Creating admin user "kbond"')
            ->assertErrorOutputContains('this is in stderr') // used in conjunction with ->splitOutputStreams()
            ->assertErrorOutputNotContains('admin user') // used in conjunction with ->splitOutputStreams()
            ->dump() // dump() the status code/outputs and continue
            ->dd() // dd() the status code/outputs
        ;

        // testing interactive commands
        $this->executeConsoleCommand('create:user', ['kbond'])
            ->assertSuccessful()
            ->assertOutputContains('Creating regular user "kbond"')
        ;

        // advanced testing interactive commands
        $this->consoleCommand(CreateUserCommand::class)
            ->addInput('kbond')
            ->addOption('--no-interaction') // commands are run interactively if input is provided, use this option to disable
            ->execute()
            ->assertSuccessful()
            ->assertOutputContains('Creating regular user "kbond"')
        ;

        // access result
        $result = $this->executeConsoleCommand('create:user');

        $result->statusCode();
        $result->output();
        $result->errorOutput();
    }
}
```

Или:

```
use App\Command\CreateUserCommand;
use PHPUnit\Framework\TestCase;
use Prokl\TestingTools\Tools\Console\TestCommand;

class CreateUserCommandTest extends TestCase
{
    public function test_can_create_user(): void
    {
        TestCommand::for(new CreateUserCommand(/** args... */))
            ->splitOutputStreams() // by default stdout/stderr are combined, this options splits them
            ->addArgument('kbond')
            ->addOption('--admin') // with or without "--" prefix
            ->addOption('role', ['ROLE_EMPLOYEE', 'ROLE_MANAGER'])
            ->addOption('-R') // shortcut options require the "-" prefix
            ->addOption('-vv') // by default, output has normal verbosity, use the standard options to change (-q, -v, -vv, -vvv)
            ->addOption('--ansi') // by default, output is undecorated, use this option to decorate
            ->execute()
            ->assertSuccessful()
            ->assertStatusCode(0) // equivalent to ->assertSuccessful()
            ->assertOutputContains('Creating admin user "kbond"')
            ->assertErrorOutputContains('this is in stderr') // used in conjunction with ->splitOutputStreams()
            ->assertErrorOutputNotContains('admin user') // used in conjunction with ->splitOutputStreams()
            ->dump() // dump() the status code/outputs and continue
            ->dd() // dd() the status code/outputs
        ;

        // testing interactive commands
        TestCommand::for(new CreateUserCommand(/** args... */))
            ->addInput('kbond')
            ->addOption('--no-interaction') // commands are run interactively if input is provided, use this option to disable
            ->execute()
            ->assertSuccessful()
            ->assertOutputContains('Creating regular user "kbond"')
        ;

        // access result
        $result = TestCommand::for(new CreateUserCommand(/** args... */))->execute();

        $result->statusCode();
        $result->output();
        $result->errorOutput();
    }
}
```

Прочее
------

[](#прочее)

### Invader ([из пакета](https://github.com/spatie/invade))

[](#invader-из-пакета)

```
class MyClass
{
    private string $privateProperty = 'private value';

    private function privateMethod(): string
    {
        return 'private return value';
    }
}

$myClass = new Myclass();
```

This is how you can get the value of the private property using the `invade` function.

```
invade($myClass)->privateProperty; // returns 'private value'
```

The `invade` function also allows you to change private values.

```
invade($myClass)->privateProperty = 'changed value';
invade($myClass)->privateProperty; // returns 'changed value
```

Using `invade` you can also call private functions.

```
invade($myClass)->privateMethod(); // returns 'private return value'
```

###  Health Score

32

—

LowBetter than 69% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community19

Small or concentrated contributor base

Maturity66

Established project with proven stability

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~13 days

Recently: every ~150 days

Total

58

Last Release

1140d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9210c86ee6734e537eaf22c0f2fe7a965451e340e39e1aae2b74013f24c2660d?d=identicon)[gedovan](/maintainers/gedovan)

---

Top Contributors

[![ProklUng](https://avatars.githubusercontent.com/u/19857467?v=4)](https://github.com/ProklUng "ProklUng (76 commits)")

---

Tags

php7phpunittesting

### Embed Badge

![Health badge](/badges/proklung-phpunit-testing-tools/health.svg)

```
[![Health](https://phpackages.com/badges/proklung-phpunit-testing-tools/health.svg)](https://phpackages.com/packages/proklung-phpunit-testing-tools)
```

###  Alternatives

[shopware/core

Shopware platform is the core for all Shopware ecommerce products.

585.4M514](/packages/shopware-core)[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.5k5.8M712](/packages/sylius-sylius)[open-dxp/opendxp

Content &amp; Product Management Framework (CMS/PIM)

9317.2k55](/packages/open-dxp-opendxp)[pimcore/pimcore

Content &amp; Product Management Framework (CMS/PIM/E-Commerce)

3.8k3.8M462](/packages/pimcore-pimcore)[chameleon-system/chameleon-base

The Chameleon System core.

1027.9k4](/packages/chameleon-system-chameleon-base)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.4M196](/packages/sulu-sulu)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
