bricre/symfony-bundle-test

Supportive classes for testing Symfony private services

0.1 2020-12-04 11:51 UTC

This package is auto-updated.

Last update: 2024-10-24 23:23:10 UTC


README

Inspired by https://github.com/SymfonyTest/symfony-bundle-test

Test Symfony Private Services easily

Symfony has already provided a way to test private services since 4.1, it only allows non-removed private services. This is not enough, especially when we develop a Symfony Bunddle. By default, we can create a lot of private services in a bundle, but when writing tests dedicated for the bundle theses services would not be testable because they were not used in any actual codes yet hence would be removed by Symfony.

The solution would be deliberately marking these services as public, so we can fetch them to do integration test.

Installation

Via composer

composer require --dev bricre/symfony-bundle-test

Write a test

<?php
use Bricre\SymfonyTest\BaseBundleTestCase;
use Acme\AcmeFooBundle;
use Acme\Service\Foo;

class BundleInitializationTest extends BaseBundleTestCase
{
    protected function getBundleClass():string
    {
        return AcmeFooBundle::class;
    }

    public function testInitBundle()
    {
        // Boot the kernel.
        $this->bootKernel();

        // Get the container
        $container = $this->getContainer();

        // Test if you services exists
        $this->assertTrue($container->has('acme.foo'));
        $service = $container->get('acme.foo');
        $this->assertInstanceOf(Foo::class, $service);
    }

    public function testBundleWithDifferentConfiguration()
    {
        // Create a new Kernel
        $kernel = $this->createKernel();

        // Add some configuration
        $kernel->addConfigFile(__DIR__.'/config.yml');

        // Add some other bundles we depend on
        $kernel->addBundle(OtherBundle::class);

        // Boot the kernel as normal ...
        $this->bootKernel();

        // ...
    }
}

MicroBundleTestCase vs FrameworkedBundleTestCase

The MicroBundleTestCase is a minimal bundle test case with the least overhead to bootstrap a bundle test. It will not include any bundles by default.

In real life environment your bundle would often depend on the FrameworkBundle, so a FrameworkedBundleTestCase is created for you with some default configuration ready.

<?php
use Bricre\SymfonyTest\FrameworkedBundleTestCase;

class BundleInitializationTest extends FrameworkedBundleTestCase
{
}

The default configurations is loaded from

|/vendor/
|----/bricre/
|--------/symfony-bundle-test/
|------------/src/
|----------------/config/
|--------------------framework.yml
|--------------------routing.yml
|--------------------...

If you want to customise the config, just create a config folder in your own bundle as if it was in a Symfony project

|/config/
|----framework.yml
|----routing.yml
|----...
|/src/
|/vendor/