/phpunit-service-factory-trait

phpunit-service-factory is a lightweight and reusable PHPUnit trait that simplifies the creation and injection of services in your unit tests. Designed for modern PHP applications, this trait helps you quickly bootstrap services—either from your service container or through manual instantiation—without repetitive boilerplate code.

Primary LanguagePHP

PHPUnit Service Factory

PHP Version License: MIT

A lightweight and reusable PHPUnit trait that simplifies the creation and injection of services in your unit tests. Designed for modern PHP applications, this trait helps you quickly bootstrap services—either from your service container or through manual instantiation—without repetitive boilerplate code.

Perfect for testing applications that rely on dependency injection, service containers (like Symfony, Laravel, or custom containers), and mocking service behaviors. Whether you're writing isolated unit tests or integration tests, this trait streamlines your test setup and keeps your test code clean and maintainable.

Installation

Install the package with Composer:

composer require --dev wk/phpunit-service-factory

Usage

To use the trait, simply use it in your PHPUnit test class. This will give you access to the createService method, which can instantiate services and their dependencies for you.

Here's a basic example:

// class extending PHPUnit\Framework\TestCase
    use ServiceFactoryTrait;

    private mixed $service;

    protected function setUp(): void
    {
        $this->service = $this->createInstanceWithMockedDependencies(A::class);
    }

License

This project is licensed under the MIT License.

Authors