Skip to content

Testing

github-actions[bot] edited this page Jun 25, 2026 · 1 revision

Тестирование

Unit-тесты

Создавайте новый Container в каждом тесте — экземпляры не разделяют состояние:

final class OrderServiceTest extends TestCase
{
    public function testCreatesOrder(): void
    {
        $container = new Container();
        $container->set('clock', new FixedClock('2026-01-01'));
        $container->set(
            'orders',
            static fn (ContainerInterface $c): OrderService => new OrderService($c->get('clock')),
        );

        $service = $container->get('orders');
        // assertions...
    }
}

Autowiring в тестах

$container = new Container();
$container->enableAutowiring();
$container->set(ClockInterface::class, new FixedClock('2026-01-01'));

$service = $container->get(OrderService::class);

Property и method injection в тестах:

$container = new Container();
$container->enableAutowiring();
$container->enablePropertyAutowiring();
$container->enableMethodAutowiring();
$container->set(LoggerInterface::class, new NullLogger());

$service = $container->get(LegacyServiceWithSetters::class);

Явный set() переопределяет autowiring для того же типа.

Подмена зависимостей

Зарегистрируйте тестовый double до первого get():

$container->set('mailer', $this->createMock(MailerInterface::class));

После get() замена через set() сбросит кэш — при следующем get() будет новый singleton.

ContainerRegistry

Если тесты используют глобальный реестр, сбрасывайте его:

protected function tearDown(): void
{
    ContainerRegistry::reset();
    parent::tearDown();
}

public function testWithRegistry(): void
{
    $container = new Container();
    $container->set('clock', new FixedClock());
    ContainerRegistry::set($container);

    // код, вызывающий ContainerRegistry::get()
}

Предпочтительнее передавать Container явно — без глобального состояния.

Интеграционные тесты

Вынесите регистрацию сервисов в функцию или класс:

function createApplicationContainer(): Container
{
    $container = new Container();
    $container->enableAutowiring();
    $container->scan(__DIR__ . '/../src/Services', 'App\\Services\\');
    // test doubles...
    return $container;
}

Команды в репозитории

composer test:unit
composer test:integration
composer test:security
composer ci

Покрытие и мутации

composer test:coverage   # порог ≥95% строк
composer test:mutation   # Infection MSI ≥95%

Требуется PCOV или Xdebug (XDEBUG_MODE=coverage).

Clone this wiki locally