All Projects → SymfonyTest → Symfonydependencyinjectiontest

SymfonyTest / Symfonydependencyinjectiontest

Licence: mit
Library for testing user classes related to the Symfony Dependency Injection Component

Labels

Projects that are alternatives of or similar to Symfonydependencyinjectiontest

Daemonizable Command
Daemonizable (endless running) commands for Symfony.
Stars: ✭ 189 (-8.25%)
Mutual labels:  symfony
Stopwatch
The Stopwatch component provides a way to profile code.
Stars: ✭ 2,388 (+1059.22%)
Mutual labels:  symfony
Rich Model Forms Bundle
Provides additional data mappers that ease the use of the Symfony Form component with rich models.
Stars: ✭ 198 (-3.88%)
Mutual labels:  symfony
Backbee Php
the next generation CMS built on top of Symfony and Doctrine components. Give us a star to support our project :)
Stars: ✭ 192 (-6.8%)
Mutual labels:  symfony
Mercure Bundle
The MercureBundle allows to easily push updates to web browsers and other HTTP clients in the Symfony full-stack framework, using the Mercure protocol.
Stars: ✭ 195 (-5.34%)
Mutual labels:  symfony
Inflector
Inflector converts words between their singular and plural forms (English only).
Stars: ✭ 2,232 (+983.5%)
Mutual labels:  symfony
Intl
A PHP replacement layer for the C intl extension that also provides access to the localization data of the ICU library.
Stars: ✭ 2,323 (+1027.67%)
Mutual labels:  symfony
Liiphellobundle
[DEPRECATED] Alternative Hello World Bundle for Symfony2 using several FriendsOfSymfony Bundles
Stars: ✭ 206 (+0%)
Mutual labels:  symfony
Phpenums
🔩 Provides enumerations for PHP & frameworks integrations
Stars: ✭ 194 (-5.83%)
Mutual labels:  symfony
Form
The Form component allows you to easily create, process and reuse HTML forms.
Stars: ✭ 2,406 (+1067.96%)
Mutual labels:  symfony
Property Access
The PropertyAccess component provides function to read and write from/to an object or array using a simple string notation.
Stars: ✭ 2,362 (+1046.6%)
Mutual labels:  symfony
Symfony1
The official Git mirror for symfony 1.x
Stars: ✭ 194 (-5.83%)
Mutual labels:  symfony
Angular Symfony
Project Bootstrap for an Angular + Symfony project
Stars: ✭ 196 (-4.85%)
Mutual labels:  symfony
Book 5.0 1
The Symfony 5 book source: The Fast Track
Stars: ✭ 192 (-6.8%)
Mutual labels:  symfony
Expression Language
The ExpressionLanguage component provides an engine that can compile and evaluate expressions.
Stars: ✭ 2,418 (+1073.79%)
Mutual labels:  symfony
Polyfill Intl Icu
This component provides a collection of functions/classes using the symfony/intl package when the Intl extension is not installed.
Stars: ✭ 2,287 (+1010.19%)
Mutual labels:  symfony
Alice
Expressive fixtures generator
Stars: ✭ 2,289 (+1011.17%)
Mutual labels:  symfony
Event Dispatcher Contracts
A set of event dispatcher abstractions extracted out of the Symfony components
Stars: ✭ 2,667 (+1194.66%)
Mutual labels:  symfony
Panther
A browser testing and web crawling library for PHP and Symfony
Stars: ✭ 2,480 (+1103.88%)
Mutual labels:  symfony
Gifexceptionbundle
😛 The GhostBuster of your exception page!
Stars: ✭ 197 (-4.37%)
Mutual labels:  symfony

SymfonyDependencyInjectionTest

By Matthias Noback and contributors

Build Status

This library contains several PHPUnit test case classes and many semantic assertions which you can use to functionally test your container extensions (or "bundle extensions") and compiler passes. It also provides the tools to functionally test your container extension (or "bundle") configuration by verifying processed values from different types of configuration files.

Besides verifying their correctness, this library will also help you to adopt a TDD approach when developing these classes.

Installation

Using Composer:

php composer.phar require --dev matthiasnoback/symfony-dependency-injection-test

Usage

Testing a container extension

To test your own container extension class MyExtension create a class and extend from Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase. Then implement the getContainerExtensions() method:

<?php

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionTestCase;

class MyExtensionTest extends AbstractExtensionTestCase
{
    protected function getContainerExtensions(): array
    {
        return array(
            new MyExtension()
        );
    }
}

Basically you will be testing your extension's load method, which will look something like this:

<?php

class MyExtension extends Extension
{
    public function load(array $config, ContainerBuilder $container)
    {
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__));
        $loader->load('services.xml');

        // maybe process the configuration values in $config, then:

        $container->setParameter('parameter_name', 'some value');
    }
}

So in the test case you should test that after loading the container, the parameter has been set correctly:

<?php

class MyExtensionTest extends AbstractExtensionTestCase
{
    /**
     * @test
     */
    public function after_loading_the_correct_parameter_has_been_set()
    {
        $this->load();

        $this->assertContainerBuilderHasParameter('parameter_name', 'some value');
    }
}

To test the effect of different configuration values, use the first argument of load():

<?php

class MyExtensionTest extends AbstractExtensionTestCase
{
    /**
     * @test
     */
    public function after_loading_the_correct_parameter_has_been_set()
    {
        $this->load(array('my' => array('enabled' => 'false')));

        ...
    }
}

To prevent duplication of required configuration values, you can provide some minimal configuration, by overriding the getMinimalConfiguration() method of the test case.

Testing a compiler pass

To test a compiler pass, create a test class and extend from Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase. Then implement the registerCompilerPass() method:

<?php

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractCompilerPassTestCase;

class MyCompilerPassTest extends AbstractCompilerPassTestCase
{
    protected function registerCompilerPass(ContainerBuilder $container): void
    {
        $container->addCompilerPass(new MyCompilerPass());
    }
}

In each test you can first set up the ContainerBuilder instance properly, depending on what your compiler pass is expected to do. For instance you can add some definitions with specific tags you will collect. Then after the "arrange" phase of your test, you need to "act", by calling the compile()method. Finally you may enter the "assert" stage and you should verify the correct behavior of the compiler pass by making assertions about the ContainerBuilder instance.

<?php

class MyCompilerPassTest extends AbstractCompilerPassTestCase
{
    /**
     * @test
     */
    public function if_compiler_pass_collects_services_by_adding_method_calls_these_will_exist()
    {
        $collectingService = new Definition();
        $this->setDefinition('collecting_service_id', $collectingService);

        $collectedService = new Definition();
        $collectedService->addTag('collect_with_method_calls');
        $this->setDefinition('collected_service', $collectedService);

        $this->compile();

        $this->assertContainerBuilderHasServiceDefinitionWithMethodCall(
            'collecting_service_id',
            'add',
            array(
                new Reference('collected_service')
            )
        );
    }
}

Standard test for unobtrusiveness

The AbstractCompilerPassTestCase class always executes one specific test - compilation_should_not_fail_with_empty_container() - which makes sure that the compiler pass is unobtrusive. For example, when your compiler pass assumes the existence of a service, an exception will be thrown, and this test will fail:

<?php

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class MyCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        $definition = $container->getDefinition('some_service_id');

        ...
    }
}

So you need to always add one or more guard clauses inside the process() method:

<?php

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class MyCompilerPass implements CompilerPassInterface
{
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('some_service_id')) {
            return;
        }

        $definition = $container->getDefinition('some_service_id');

        ...
    }
}

Use findDefinition() instead of getDefinition()

You may not know in advance if a service id stands for a service definition, or for an alias. So instead of hasDefinition() and getDefinition() you may consider using has() and findDefinition(). These methods recognize both aliases and definitions.

Test different configuration file formats

The Symfony DependencyInjection component supports many different types of configuration loaders: Yaml, XML, and PHP files, but also closures. When you create a Configuration class for your bundle, you need to make sure that each of these formats is supported. Special attention needs to be given to XML files.

In order to verify that any type of configuration file will be correctly loaded by your bundle, you must install the SymfonyConfigTest library and create a test class that extends from AbstractExtensionConfigurationTestCase:

<?php

use Matthias\SymfonyDependencyInjectionTest\PhpUnit\AbstractExtensionConfigurationTestCase;

class ConfigurationTest extends AbstractExtensionConfigurationTestCase
{
    protected function getContainerExtension()
    {
        return new TwigExtension();
    }

    protected function getConfiguration()
    {
        return new Configuration();
    }
}

Now inside each test method you can use the assertProcessedConfigurationEquals($expectedConfiguration, $sources) method to verify that after loading the given sources the processed configuration equals the expected array of values:

# in Fixtures/config.yml
twig:
    extensions: ['twig.extension.foo']
<!-- in Fixtures/config.xml -->
<container>
    <twig:config>
        <twig:extension>twig.extension.bar</twig:extension>
    </twig:config>
</container>
<?php
...

class ConfigurationTest extends AbstractExtensionConfigurationTestCase
{
    ...

    /**
     * @test
     */
    public function it_converts_extension_elements_to_extensions()
    {
        $expectedConfiguration = array(
            'extensions' => array('twig.extension.foo', 'twig.extension.bar')
        );

        $sources = array(
            __DIR__ . '/Fixtures/config.yml',
            __DIR__ . '/Fixtures/config.xml',
        );

        $this->assertProcessedConfigurationEquals($expectedConfiguration, $sources);
    }
}

List of assertions

These are the available semantic assertions for each of the test cases shown above:

assertContainerBuilderHasService($serviceId)
Assert that the ContainerBuilder for this test has a service definition with the given id.
assertContainerBuilderHasService($serviceId, $expectedClass)
Assert that the ContainerBuilder for this test has a service definition with the given id and class.
assertContainerBuilderNotHasService($serviceId)
Assert that the ContainerBuilder for this test does not have a service definition with the given id.
assertContainerBuilderHasSyntheticService($serviceId)
Assert that the ContainerBuilder for this test has a synthetic service with the given id.
assertContainerBuilderHasAlias($aliasId)
Assert that the ContainerBuilder for this test has an alias.
assertContainerBuilderHasAlias($aliasId, $expectedServiceId)
Assert that the ContainerBuilder for this test has an alias and that it is an alias for the given service id.
assertContainerBuilderHasParameter($parameterName)
Assert that the ContainerBuilder for this test has a parameter.
assertContainerBuilderHasParameter($parameterName, $expectedParameterValue)
Assert that the ContainerBuilder for this test has a parameter and that its value is the given value.
assertContainerBuilderHasServiceDefinitionWithArgument($serviceId, $argumentIndex)
Assert that the ContainerBuilder for this test has a service definition with the given id, which has an argument at the given index.
assertContainerBuilderHasServiceDefinitionWithArgument($serviceId, $argumentIndex, $expectedValue)
Assert that the ContainerBuilder for this test has a service definition with the given id, which has an argument at the given index, and its value is the given value.
assertContainerBuilderHasServiceDefinitionWithServiceLocatorArgument($serviceId, $argumentIndex, $expectedValue)
Assert that the ContainerBuilder for this test has a service definition with the given id, which has an argument at the given index, and its value is a ServiceLocator with a reference-map equal to the given value.
assertContainerBuilderHasServiceDefinitionWithMethodCall($serviceId, $method, array $arguments = array(), $index = null)
Assert that the ContainerBuilder for this test has a service definition with the given id, which has a method call to the given method with the given arguments. If index is provided, invocation index order of method call is asserted as well.
assertContainerBuilderHasServiceDefinitionWithTag($serviceId, $tag, array $attributes = array())
Assert that the ContainerBuilder for this test has a service definition with the given id, which has the given tag with the given arguments.
assertContainerBuilderHasServiceDefinitionWithParent($serviceId, $parentServiceId)
Assert that the ContainerBuilder for this test has a service definition with the given id which is a decorated service and it has the given parent service.
assertContainerBuilderHasServiceLocator($serviceId, $expectedServiceMap)
Assert that the ContainerBuilder for this test has a ServiceLocator service definition with the given id.

Available methods to set up container

In all test cases shown above, you have access to some methods to set up the container:

setDefinition($serviceId, $definition)
Set a definition. The second parameter is a Definition class
registerService($serviceId, $class)
A shortcut for setDefinition. It returns a Definition object that can be modified if necessary.
setParameter($parameterId, $parameterValue)
Set a parameter.

Version Guidance

Version Released PHPUnit Status
4.x Mar 28, 2019 8.x Latest
3.x Mar 5, 2018 7.x Bugfixes
2.x May 9, 2017 6.x Bugfixes
1.x Jul 4, 2016 4.x and 5x EOL
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].