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!
The
.envfile is only used indevenvironment. If you're inprodor intest, 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
configfolder, more specifically probably underconfig/packages/doctrine.yamlandconfig/packages/parameters.yaml, and see how theDATABASE_URLis used (when it exists). From there, you can either hardcode that URL in config files specific to thetestenvironment (creating atestsubfolder underconfig/packagesfor instance), or you can give the properDATABASE_URLenvironment variable tophpunit"manually" by usingAPP_ENV=... && bin/phpunit ....Here's what a solution would look like in the first scenario :