Symfony4: Doctrine2 works but no connection in PHPUnit test (kernel booted)

…衆ロ難τιáo~ 提交于 2019-12-19 17:35:30

问题


Strange issue in Symfony4: Doctrine works, I can validate the schema, create the database etc using php bin/console doctrine:schema:create. But my PHPUnit test does not have a connection. By running ./bin/phpunit I get SQLSTATE[HY000] [2002] No such file or directory exception.

I followed the steps within the docs regarding booting up the kernel: http://symfony.com/doc/current/testing/doctrine.html

My code:

class PersistingResultTest extends KernelTestCase
{
    protected $em;

    protected function setUp()
    {
        $kernel = self::bootKernel();

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

    public function testPersistingLogFile()
    {
        // Just a simple schema command to test connection
        $tool = new SchemaTool($this->em);
        $tool->createSchema($this->em->getMetadataFactory()->getAllMetadata());
    }


   protected function tearDown()
    {
        parent::tearDown();

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

Anyone know why this happens? A bug?

EDIT:

Apparently the .env file is not read properly. I moved the DATABASE_URL environment variable into the doctrine.yml file and now it works.


回答1:


You have to put the DATABASE_URL into your phpunit.xml file, e.g. like this:

<php>
        <ini name="error_reporting" value="-1" />
        <env name="KERNEL_CLASS" value="App\Kernel" />
        <env name="APP_ENV" value="test" />

        <!-- ###+ doctrine/doctrine-bundle ### -->
        <!-- Format described at http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url -->
        <!-- For an SQLite database, use: "sqlite:///%kernel.project_dir%/var/data.db" -->
        <!-- Configure your db driver and server_version in config/packages/doctrine.yaml -->
        <env name="DATABASE_URL" value="mysql://root@127.0.0.1:3306/symfony4-database"/>
        <!-- ###- doctrine/doctrine-bundle ### -->
    </php>


来源:https://stackoverflow.com/questions/48171095/symfony4-doctrine2-works-but-no-connection-in-phpunit-test-kernel-booted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!