PHPackages                             shopsys/phpunit-injector - 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. shopsys/phpunit-injector

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

shopsys/phpunit-injector
========================

Injects services from a PSR-11 dependency injection container to PHPUnit test cases

2.7.0(2mo ago)033.9k↓19.7%1MITPHPPHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0

Since Dec 5Pushed 2mo agoCompare

[ Source](https://github.com/shopsys/phpunit-injector)[ Packagist](https://packagist.org/packages/shopsys/phpunit-injector)[ GitHub Sponsors](https://github.com/jakzal)[ RSS](/packages/shopsys-phpunit-injector/feed)WikiDiscussions 2.5 Synced 1mo ago

READMEChangelog (2)Dependencies (11)Versions (6)Used By (1)

PHPUnit Injector
================

[](#phpunit-injector)

[![Build](https://github.com/jakzal/phpunit-injector/actions/workflows/build.yml/badge.svg)](https://github.com/jakzal/phpunit-injector/actions/workflows/build.yml)

Provides a PHPUnit listener to inject services from a PSR-11 dependency injection container to PHPUnit test cases.

Services are injected to test cases that implement `Zalas\Injector\PHPUnit\TestCase\ServiceContainerTestCase`to any property tagged with `@inject`.

[Symfony DependencyInjection component](https://github.com/symfony/dependency-injection) integration is also provided.

Installation
------------

[](#installation)

### Composer

[](#composer)

```
composer require --dev zalas/phpunit-injector
```

### Phar

[](#phar)

The extension is also distributed as a PHAR, which can be downloaded from the most recent [Github Release](https://github.com/jakzal/phpunit-injector/releases).

Put the extension in your PHPUnit extensions directory. Remember to instruct PHPUnit to load extensions in your `phpunit.xml`:

```

```

Configuration
-------------

[](#configuration)

Enable the service injector listener in the [PHPUnit configuration file](https://phpunit.de/manual/current/en/appendixes.configuration.html):

```

```

Usage
-----

[](#usage)

To inject services using any PSR-11 service container, implement the `Zalas\Injector\PHPUnit\TestCase\ServiceContainerTestCase`and tag selected properties with `@inject`:

```
use PHPUnit\Framework\TestCase;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Zalas\Injector\PHPUnit\TestCase\ServiceContainerTestCase;

class ServiceInjectorTest extends TestCase implements ServiceContainerTestCase
{
    /**
     * @inject
     */
    private SerializerInterface $serializer;

    /**
     * @inject logger
     */
    private LoggerInterface $logger;

    public function testThatServicesAreInjected()
    {
        $this->assertInstanceOf(SerializerInterface::class, $this->serializer, 'The service is injectd by its type');
        $this->assertInstanceOf(LoggerInterface::class, $this->logger, 'The service is injected by its id');
    }

    public function createServiceContainer(): ContainerInterface
    {
        // create a service container here
    }
}
```

The service is found by its type, or an id if it's given in the `@inject` tag.

The `createServiceContainer` method would be usually provided by a base test case or a trait. In case of Symfony, such a trait is provided by this package (see the next section).

### Symfony Test Container (Symfony &gt;= 4.1)

[](#symfony-test-container-symfony--41)

The `Zalas\Injector\PHPUnit\Symfony\TestCase\SymfonyTestContainer` trait provides access to the test container ([introduced in Symfony 4.1](https://symfony.com/blog/new-in-symfony-4-1-simpler-service-testing)). Including the trait in a test case implementing the `ServiceContainerTestCase` will make that services are injected into annotated properties:

```
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Zalas\Injector\PHPUnit\Symfony\TestCase\SymfonyTestContainer;
use Zalas\Injector\PHPUnit\TestCase\ServiceContainerTestCase;

class ServiceInjectorTest extends TestCase implements ServiceContainerTestCase
{
    use SymfonyTestContainer;

    /**
     * @inject
     */
    private SerializerInterface $serializer;

    /**
     * @inject logger
     */
    private LoggerInterface $logger;

    public function testThatServicesAreInjected()
    {
        $this->assertInstanceOf(SerializerInterface::class, $this->serializer, 'The service is injectd by its type');
        $this->assertInstanceOf(LoggerInterface::class, $this->logger, 'The service is injected by its id');
    }
}
```

Note that `test` needs to be set to `true` in your test environment configuration for the framework bundle:

```
framework:
    test: true
```

Even though services are automatically made private by Symfony, the test container makes them available in your tests. Note that this only happens for private services that are actually used in your app (so are injected into a public service, i.e. a controller). If a service is not injected anywhere, it's removed by the container compiler.

The kernel used to bootstrap the container is created in a similar way to the `KernelTestCase` known from the FrameworkBundle. Similar environment variables are supported:

- `KERNEL_CLASS` *required* - kernel class to instantiate to create the service container
- `APP_ENV` default: test - kernel environment
- `APP_DEBUG` default: false - kernel debug flag

These could for example be configured in `phpunit.xml`, or via [global variables](https://github.com/jakzal/phpunit-globals).

### Symfony Container (Symfony 3.4 &amp; 4.0)

[](#symfony-container-symfony-34--40)

The `Zalas\Injector\PHPUnit\Symfony\TestCase\SymfonyContainer` trait gives access to the full Symfony Container and can be used with any Symfony version. Opposed to the Test Container approach for Symfony 4.1, this version provides access to each service even if it's not used by your application anywhere and would normally be removed by the compiler. This should be treated as a limitation rather than a feature.

```
use PHPUnit\Framework\TestCase;
use Psr\Log\LoggerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Zalas\Injector\PHPUnit\Symfony\TestCase\SymfonyContainer;
use Zalas\Injector\PHPUnit\TestCase\ServiceContainerTestCase;

class ServiceInjectorTest extends TestCase implements ServiceContainerTestCase
{
    use SymfonyContainer;

    /**
     * @inject
     */
    private SerializerInterface $serializer;

    /**
     * @inject logger
     */
    private LoggerInterface $logger;

    public function testThatServicesAreInjected()
    {
        $this->assertInstanceOf(SerializerInterface::class, $this->serializer, 'The service is injectd by its type');
        $this->assertInstanceOf(LoggerInterface::class, $this->logger, 'The service is injected by its id');
    }
}
```

Since the test container is not available until Symfony 4.1, you'll also have to register the `Zalas\Injector\PHPUnit\Symfony\Compiler\ExposeServicesForTestsPass` compiler pass:

```
use Zalas\Injector\PHPUnit\Symfony\Compiler\ExposeServicesForTestsPass;

class Kernel extends BaseKernel
{
    // ...

    protected function build(ContainerBuilder $container)
    {
        if ('test' === $this->getEnvironment()) {
            $container->addCompilerPass(new ExposeServicesForTestsPass());
        }
    }
}
```

The compiler pass makes sure that even private services are available to be used in tests.

Contributing
------------

[](#contributing)

Please read the [Contributing guide](CONTRIBUTING.md) to learn about contributing to this project. Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project you agree to abide by its terms.

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance83

Actively maintained with recent releases

Popularity30

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 94.1% 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 ~15 days

Total

6

Last Release

88d ago

PHP version history (2 changes)2.5.1PHP ~8.1.0 || ~8.2.0 || ~8.3.0

2.7.0PHP ~8.1.0 || ~8.2.0 || ~8.3.0 || ~8.4.0 || ~8.5.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/0e3409c555d1e101617340d2ba982d26d5c28a2b1dbf10e7e19b8a07e6a7eed5?d=identicon)[TomasLudvik](/maintainers/TomasLudvik)

---

Top Contributors

[![jakzal](https://avatars.githubusercontent.com/u/190447?v=4)](https://github.com/jakzal "jakzal (175 commits)")[![gjuric](https://avatars.githubusercontent.com/u/223015?v=4)](https://github.com/gjuric "gjuric (3 commits)")[![grossmannmartin](https://avatars.githubusercontent.com/u/1177414?v=4)](https://github.com/grossmannmartin "grossmannmartin (3 commits)")[![TomasLudvik](https://avatars.githubusercontent.com/u/5638367?v=4)](https://github.com/TomasLudvik "TomasLudvik (3 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (1 commits)")[![villfa](https://avatars.githubusercontent.com/u/2891564?v=4)](https://github.com/villfa "villfa (1 commits)")

### Embed Badge

![Health badge](/badges/shopsys-phpunit-injector/health.svg)

```
[![Health](https://phpackages.com/badges/shopsys-phpunit-injector/health.svg)](https://phpackages.com/packages/shopsys-phpunit-injector)
```

###  Alternatives

[behat/behat

Scenario-oriented BDD framework for PHP

4.0k96.8M2.0k](/packages/behat-behat)[typo3/testing-framework

The TYPO3 testing framework provides base classes for unit, functional and acceptance testing.

675.0M775](/packages/typo3-testing-framework)[timacdonald/log-fake

A drop in fake logger for testing with the Laravel framework.

4235.9M56](/packages/timacdonald-log-fake)[jasonmccreary/laravel-test-assertions

A set of helpful assertions when testing Laravel applications.

3513.9M32](/packages/jasonmccreary-laravel-test-assertions)[ergebnis/phpunit-slow-test-detector

Provides facilities for detecting slow tests in phpunit/phpunit.

1468.1M72](/packages/ergebnis-phpunit-slow-test-detector)[zalas/phpunit-injector

Injects services from a PSR-11 dependency injection container to PHPUnit test cases

62346.2k](/packages/zalas-phpunit-injector)

PHPackages © 2026

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