【问题标题】:Symfony4: Doctrine2 works but no connection in PHPUnit test (kernel booted)Symfony4:Doctrine2 工作,但在 PHPUnit 测试中没有连接(内核启动)
【发布时间】:2018-01-09 15:06:41
【问题描述】:

Symfony4 中的奇怪问题:Doctrine 有效,我可以使用 php bin/console doctrine:schema:create 验证架构、创建数据库等。但是我的 PHPUnit 测试没有连接。通过运行./bin/phpunit 我得到SQLSTATE[HY000] [2002] No such file or directory 异常。

我按照文档中有关启动内核的步骤进行操作: http://symfony.com/doc/current/testing/doctrine.html

我的代码:

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

有人知道为什么会这样吗?一个错误?

编辑:

显然.env 文件没有被正确读取。我将DATABASE_URL 环境变量移动到doctrine.yml 文件中,现在它可以工作了。

【问题讨论】:

    标签: php symfony doctrine-orm symfony4


    【解决方案1】:

    您必须将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>
    

    【讨论】:

    • 或者您也可以使用 SQLite 数据库,它速度更快,并且不会冒险更改您的真实数据库!
    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 2012-08-12
    • 2013-08-29
    • 2019-10-22
    • 2019-05-14
    • 2013-01-24
    • 2012-11-15
    • 1970-01-01
    相关资源
    最近更新 更多