Skip to content

Instantly share code, notes, and snippets.

@bmichalski
Last active September 13, 2015 12:40
Show Gist options
  • Save bmichalski/96a63c220e6e812254c0 to your computer and use it in GitHub Desktop.
Save bmichalski/96a63c220e6e812254c0 to your computer and use it in GitHub Desktop.
Symfony2 functional testing using Doctrine, sharing connections between requests
#app/config/config_test_functional.yml
imports:
- { resource: config_test.yml }
namespace BenMichalski\AppBundle\Test\Client;
/**
* Heavily inspired by http://alexandre-salome.fr/blog/Symfony2-Isolation-Of-Tests
*/
class SharedDoctrineConnectionsClient extends BaseClient
{
/**
* @var array
*/
protected $connectionsByServiceId;
/**
* @var bool
*/
protected $hasPerformedRequest = false;
/**
* {@inheritdoc}
*/
protected function doRequest($request)
{
if ($this->hasPerformedRequest) {
$this->kernel->shutdown();
$this->kernel->boot();
}
$this->handleConnections();
$this->hasPerformedRequest = true;
return $this->kernel->handle($request);
}
/**
* Saves connections to be shared if needed,
* else injects them into the container so that are shared between requests.
*/
protected function handleConnections()
{
$container = $this->getContainer();
if (null === $this->connectionsByServiceId) {
$connectionServices = $container->getParameter('doctrine.connections');
$this->connectionsByServiceId = [];
foreach ($connectionServices as $serviceId) {
$this->connectionsByServiceId[$serviceId] = $container->get($serviceId);
}
} else {
foreach ($this->connectionsByServiceId as $serviceId => $service) {
$container->set($serviceId, $service);
}
}
}
}
namespace BenMichalski\AppBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use BenMichalski\AppBundle\Test\Client\SharedDoctrineConnectionsClient;
class AppExtension extends Extension
{
/**
* {@inheritDoc}
*/
public function load(
array $configs,
ContainerBuilder $container
) {
$configuration = new Configuration();
$config = $this->processConfiguration(
$configuration,
$configs
);
$loader = new Loader\YamlFileLoader(
$container,
new FileLocator(
__DIR__
. '/../Resources/config'
)
);
$loader->load('services.yml');
if ('test_functional' === $container->getParameter('kernel.environment')) {
$container->setParameter('test.client.class', SharedDoctrineConnectionsClient::class);
}
}
}
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
class MyTest extends WebTestCase
{
/**
* {@inheritdoc}
*/
protected static function createClient(array $options = [], array $server = [])
{
$options['environment'] = 'test_functional';
return parent::createClient($options, $server);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment