PHPackages                             pkly/phpunit-service-create-trait - 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. pkly/phpunit-service-create-trait

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

pkly/phpunit-service-create-trait
=================================

A helper trait for PHPUnit 10+ for easier creation of services with dependencies in unit testing

1.1.1(2mo ago)01.6k↑63.6%9MITPHPPHP &gt;=8.4

Since Nov 27Pushed 1w ago1 watchersCompare

[ Source](https://github.com/pkly/phpunit-service-create-trait)[ Packagist](https://packagist.org/packages/pkly/phpunit-service-create-trait)[ RSS](/packages/pkly-phpunit-service-create-trait/feed)WikiDiscussions master Synced 1w ago

READMEChangelog (8)Dependencies (7)Versions (9)Used By (9)

PHPUnit Service Create Trait
============================

[](#phpunit-service-create-trait)

A helper trait for PHPUnit 12+ for easier creation of services with dependencies in unit testing

[![Packagist Downloads](https://camo.githubusercontent.com/284d8524351711e4169080d9ce59d42403bdd109ea90a8c3495d55856c572650/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f706b6c792f706870756e69742d736572766963652d6372656174652d7472616974)](https://packagist.org/packages/pkly/phpunit-service-create-trait)

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

[](#installation)

Simply run

```
composer require --dev pkly/phpunit-service-create-trait

```

Compatible with PHPUnit 12 and 13, requires PHP 8.4+

Usage
-----

[](#usage)

In any of your PHPUnit test cases simply

```
class MyTestCase extends \PHPUnit\Framework\TestCase {
    use \Pkly\ServiceMockHelperTrait;

    private AnyClass $service;

    public function setUp(): void {
        $this->service = $this->createRealMockedServiceInstance(AnyClass::class);
    }

    public function testSomething(): void
    {
        $mock = $this->createMock(MyEntity::class);

        $this->getMockedService(EntityManagerInterface::class)
            ->expects($this->once())
            ->method('delete')
            ->with($mock);

        $this->service->deleteSomething($mock);
    }
}
```

Any dependencies in the constructor as well as methods marked with Symfony's `#[Required]` attribute will be automatically plugged in with test doubles. This allows you to write complex tests without wasting time updating your construct calls each time you modify something.

### Stubs by default, mocks on demand

[](#stubs-by-default-mocks-on-demand)

PHPUnit is separating mocks from stubs and complains about every mock object that has no expectations configured (`No expectations were configured for the mock object for X ...`). Creating a mock for every single dependency would drown your test run in those notices, so every dependency is created as a double that PHPUnit does not know about - it is never verified and never complained about. Fetching one is what hands it over to the test:

- `getMockedService()` registers the double with the test case and returns it as a `MockObject`, so `expects()` is verified for you (and PHPUnit does tell you off if you then configure nothing on it)
- `getStubbedService()` returns the very same object as a `Stub`, still unregistered, for when you only need to configure return values
- everything you never fetch stays invisible to PHPUnit

The service itself is constructed immediately, so the order does not matter - expectations can be declared before or after you use it:

```
public function testSomething(): void
{
    $service = $this->createRealMockedServiceInstance(AnyClass::class);

    $this->getMockedService(EntityManagerInterface::class)
        ->expects($this->once())
        ->method('flush');

    $service->doSomething();
}
```

### Several dependencies of the same type

[](#several-dependencies-of-the-same-type)

Every parameter gets its own double, so a service depending on the same type twice receives two distinct ones. Fetching such a type without saying which parameter you mean throws a `LogicException` - pass the parameter name as the second argument:

```
$first = $this->getMockedService(BasicService::class, 'first');
$second = $this->getMockedService(BasicService::class, 'second');
```

### Several services in one test

[](#several-services-in-one-test)

`getMockedService()` and `getStubbedService()` use the most recently created service by default. Pass the service class as the third argument to address any other one:

```
$this->getMockedService(BasicService::class, service: OtherService::class);
```

### Okay, but what if I need to use something custom?

[](#okay-but-what-if-i-need-to-use-something-custom)

Simply assign the proper parameter name in either `$constructor` or `$required` in the appropriate methods. That will use your object instead of creating one for you, keep in mind you cannot retrieve it via `$this->getMockedService()`.

Some parameters always have to be provided that way:

- scalar parameters without a default value
- enums, those cannot be doubled at all

Internal classes (`\DateInterval` and friends) are handed to PHPUnit like any other type - most of them double just fine, and the ones that do not produce a precise error from PHPUnit telling you to provide it.

A nullable dependency (`?Foo`) still receives a double, pass `null` explicitly if that is what your test needs.

### Partial objects?

[](#partial-objects)

Sure, works the same, just use `createRealPartialMockedServiceInstance` instead of `createRealMockedServiceInstance`, in that case you must also specify the methods to override in your mock. Returned instance is `T&MockObject`.

Its dependencies behave exactly like the ones of a normal service - unregistered until you fetch them. The partial mock itself is a regular PHPUnit mock though, so the methods you override are subject to the usual expectation rules.

### Feature requests?

[](#feature-requests)

Sure, hit me up with an issue if you wish.

###  Health Score

51

—

FairBetter than 95% of packages

Maintenance92

Actively maintained with recent releases

Popularity20

Limited adoption so far

Community17

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 ~181 days

Recently: every ~226 days

Total

6

Last Release

88d ago

PHP version history (2 changes)1.0.0PHP &gt;=8.2

1.1.0PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/0642c17604cd51622ad504c999eb75ba78e5768bfa998eaa2922366fc90f0302?d=identicon)[pkly](/maintainers/pkly)

---

Top Contributors

[![pkly](https://avatars.githubusercontent.com/u/17160364?v=4)](https://github.com/pkly "pkly (28 commits)")

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/pkly-phpunit-service-create-trait/health.svg)

```
[![Health](https://phpackages.com/badges/pkly-phpunit-service-create-trait/health.svg)](https://phpackages.com/packages/pkly-phpunit-service-create-trait)
```

###  Alternatives

[brianium/paratest

Parallel testing for PHP

2.5k142.8M1.1k](/packages/brianium-paratest)[drupal/core-dev

require-dev dependencies from drupal/drupal; use in addition to drupal/core-recommended to run tests from drupal/core.

2023.2M367](/packages/drupal-core-dev)[webmozarts/strict-phpunit

Enables type-safe comparisons of objects in PHPUnit

31337.6k8](/packages/webmozarts-strict-phpunit)

PHPackages © 2026

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