简体   繁体   English

Symfony4:Doctrine2工作但PHPUnit测试中没有连接(内核启动)

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

Strange issue in Symfony4: Doctrine works, I can validate the schema, create the database etc using php bin/console doctrine:schema:create . Symfony4中的奇怪问题:Doctrine有效,我可以使用php bin/console doctrine:schema:create验证模式,创建数据库等。 But my PHPUnit test does not have a connection. 但我的PHPUnit测试没有连接。 By running ./bin/phpunit I get SQLSTATE[HY000] [2002] No such file or directory exception. 通过运行./bin/phpunit我得到SQLSTATE[HY000] [2002] No such file or directory异常。

I followed the steps within the docs regarding booting up the kernel: http://symfony.com/doc/current/testing/doctrine.html 我按照文档中有关启动内核的步骤进行操作: 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? 一个bug?

EDIT: 编辑:

Apparently the .env file is not read properly. 显然, .env文件无法正确读取。 I moved the DATABASE_URL environment variable into the doctrine.yml file and now it works. 我将DATABASE_URL环境变量移动到doctrine.yml文件中,现在它可以工作了。

You have to put the DATABASE_URL into your phpunit.xml file, eg like this: 您必须将DATABASE_URL放入phpunit.xml文件中,例如:

<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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM