doctrinephpunitsymfony4connectionexception

Symfony 4.1 KernelTestCase Repository ConnectionException


I'm following the symfony docs (https://symfony.com/doc/current/testing/doctrine.html) trying to test my repository classes against my MySQL database. The relevant code part is this:

class ProductRepositoryTest extends KernelTestCase
{
    /**
     * @var \Doctrine\ORM\EntityManager
     */
    private $entityManager;

    /**
     * {@inheritDoc}
     */
    protected function setUp()
    {
        $kernel = self::bootKernel();

        $this->entityManager = $kernel->getContainer()
            ->get('doctrine')
            ->getManager();
    }

    public function testSearchByCategoryName()
    {
        $products = $this->entityManager
            ->getRepository(Product::class)
            ->searchByCategoryName('foo')
        ;

        $this->assertCount(1, $products);
    }

    /**
     * {@inheritDoc}
     */
    protected function tearDown()
    {
        parent::tearDown();

        $this->entityManager->close();
        $this->entityManager = null; // avoid memory leaks
    }
}

When I execute the testclass with PhpUnit I get a Doctrine\DBAL\Exception\ConnectionException with the message: "An exception occurred in driver: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO)".

I stored my database connection data in the DATABASE_URL in the .env file and the connection works fine when executing: bin/console doctrine:migrations:migrate

But it seems this configuration is not used for testing (because 'NO' is not my password in the .env file). Do I have to store the connection configuration in another file for testing? And if yes, where do I have to store the configuration, so that it gets used in my testcase?

Thanks in advance for any help!


Solution

  • The .env file is only used in dev environment. If you're in prod or in test, it's not even read: https://symfony.com/doc/current/configuration.html#the-env-file-environment-variables. It's clear in some parts of the doc, but less in some others, which can be confusing.


    In your case, you can check your config folder, more specifically probably under config/packages/doctrine.yaml and config/packages/parameters.yaml, and see how the DATABASE_URL is used (when it exists). From there, you can either hardcode that URL in config files specific to the test environment (creating a test subfolder under config/packages for instance), or you can give the proper DATABASE_URL environment variable to phpunit "manually" by using APP_ENV=... && bin/phpunit ....

    Here's what a solution would look like in the first scenario :

    # config/packages/test/doctrine.yaml
    doctrine:
      dbal:
        url: 'mysql://db_user:db_password@127.0.0.1:3306/db_name'