Symfony PHPUnit
PHP
Testing helpers for Symfony and PHPUnit, built on Mockery. You declare a service's dependencies once and the mocks are built for you.
composer require --dev precision-soft/symfony-phpunitSymfony PHPUnit is a testing library for Symfony applications, built on Mockery. You no longer wire mocks by hand in every setUp(). A test declares the class under test and its constructor dependencies once, as a MockDto. A MockContainer then builds the whole graph lazily, nested dependencies included.
It is for teams that unit test Symfony services with many collaborators and want a declarative, reusable setup. It also ships ready-made mocks for Doctrine's ManagerRegistry, the event dispatcher and the string slugger.
Installation
Requires PHP 8.2+, Mockery 1 and Symfony PHPUnit Bridge 7 or 8.
composer require --dev precision-soft/symfony-phpunitQuick start
Extend AbstractTestCase and describe the service under test in getMockDto(). The second argument lists the constructor dependencies, the third makes it a partial mock:
use Acme\Foo\Repository\FooRepository;
use Acme\Foo\Service\CreateService;
use PrecisionSoft\Symfony\Phpunit\Mock\ManagerRegistryMock;
use PrecisionSoft\Symfony\Phpunit\MockDto;
use PrecisionSoft\Symfony\Phpunit\TestCase\AbstractTestCase;
final class CreateServiceTest extends AbstractTestCase
{
public static function getMockDto(): MockDto
{
return new MockDto(
CreateService::class,
[
ManagerRegistryMock::class,
new MockDto(FooRepository::class),
'staticDependency',
],
true,
);
}
public function testCreate(): void
{
$service = $this->get(CreateService::class);
}
}For tests that need the Symfony kernel, extend AbstractKernelTestCase instead: it extends Symfony's KernelTestCase, so self::bootKernel() and self::getContainer() are available alongside the mock container. If you need your own base class, use MockContainerTrait and implement MockDtoInterface.
MockDto
| Parameter | Type | Default | Description |
|---|---|---|---|
class | string | - | FQCN of the class or interface to mock |
construct | ?array | null | Constructor arguments; null bypasses constructor, [] calls constructor with no args |
partial | bool | false | If true, creates a partial mock via makePartial() |
onCreate | ?Closure | null | Callback invoked after mock creation for setup |
Each element of construct is resolved recursively: a MockDto instance becomes a mock, a MockDtoInterface instance or class name is resolved through its getMockDto(), and scalars are passed as they are. A reusable mock definition is just a class implementing MockDtoInterface. Cycles in the dependency graph are reported with CircularDependencyException.
Use onCreate to set default expectations right after the mock is built:
use Mockery\MockInterface;
use PrecisionSoft\Symfony\Phpunit\Container\MockContainer;
use PrecisionSoft\Symfony\Phpunit\MockDto;
public static function getMockDto(): MockDto
{
return new MockDto(
CacheInterface::class,
null,
false,
static function (MockInterface $mockInterface, MockContainer $mockContainer): void {
$mockInterface->shouldReceive('get')
->byDefault()
->andReturnUsing(static function (string $key, callable $callback) {
return $callback();
});
},
);
}Runtime registration and scoped overrides
Inside a test, registerMockDto() adds another mock configuration and registerMock() registers a pre-built Mockery double. withMock() installs a mock only for the duration of a callback, then restores the container exactly as it was, even when the callback throws:
use Mockery;
public function testFallbackPath(): void
{
$failingMockInterface = Mockery::mock(BarService::class);
$failingMockInterface->shouldReceive('process')->andThrow(new BarServiceUnavailableException());
$fallbackResult = $this->withMock(
BarService::class,
$failingMockInterface,
fn(): string => $this->get(FooService::class)->run(),
);
static::assertSame('fallback', $fallbackResult);
}Mocks created inside the scope are dropped afterwards and rebuilt on the next get(), so expectations set inside the scope do not carry over.
Built-in mocks
| Mock | Requires |
|---|---|
ManagerRegistryMock | doctrine/orm, doctrine/doctrine-bundle |
SluggerInterfaceMock | symfony/string |
EventDispatcherInterfaceMock | symfony/event-dispatcher-contracts (included via Symfony) |
ManagerRegistryMock provides a full EntityManagerInterface (persist, flush, commit, rollback, getReference and more), ClassMetadata and Connection. configureManagedEntityClasses() restricts which entities resolve to a manager, and configureRepositoryFactory() and configureClassMetadataFactory() return a different double per entity class. All three keep their state on the mock, not on the class.
The mocks cover the common paths, not all of Doctrine: Query, QueryBuilder and UnitOfWork are bare Mockery stubs, and SluggerInterfaceMock returns its input unchanged. final and readonly classes cannot be doubled through the container. The README lists every limitation.
Documentation
- README: the full reference, including
MockContainermethods, exceptions, limitations and the test conventions our suites follow - Example application: a runnable suite that exercises every public capability
- CHANGELOG