首页 > 解决方案 > PHPUnit:PDOException:SQLSTATE [HY000] [2002]连接被拒绝

问题描述

我已经有一段时间了,但我仍然不知道我在这里可能错过了什么。我在单独的 docker 容器上有 php-fpm 和 mysql,我可以从数据库中访问数据,而我的 Symfony 项目没有任何问题,除非我尝试通过 PHPUnit 运行测试,其中需要连接到数据库的测试不断返回这个错误:PDOException: SQLSTATE[HY000] [2002] Connection refused

下面是我如何设置 phpunit.xml 文件

<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="https://schema.phpunit.de/9.3/phpunit.xsd" bootstrap="vendor/autoload.php" executionOrder="depends,defects" forceCoversAnnotation="false" beStrictAboutCoversAnnotation="true" beStrictAboutOutputDuringTests="true" beStrictAboutTodoAnnotatedTests="true" verbose="true">
  <coverage>
    <include>
      <directory>src/</directory>
    </include>
  </coverage>
  <testsuites>
    <testsuite name="unit">
      <directory>test/Unit</directory>
    </testsuite>
    <testsuite name="integration">
      <directory>test/Integration</directory>
    </testsuite>
  </testsuites>
  <logging>
    <testdoxHtml outputFile="phpunit/testdox.html"/>
    <testdoxText outputFile="phpunit/testdox.txt"/>
  </logging>
  <php>
    <env name="DATABASE_URL" value="mysql://root:password@127.0.0.1:3306/proj_db?serverVersion=5.7" force="true"/>
    <env name="APP_ENV" value="dev" force="true"/>
    <env name="APP_DEBUG" value="1" force="true"/>
  </php>
</phpunit>

我什至尝试使用我SELECT user()提供的数据库地址PDOException: SQLSTATE[HY000] [2002] Connection timed out来代替。

我必须允许与正常项目分开连接吗?

编辑:我以这种方式在代码中连接到数据库

$connection = $this->getEntityManager()->getConnection();

来自连接的信息返回:

/home/user/docs/project/src/src/Proj/Infrastructure/Doctrine/Repository/RequestRepository.php:155:
array(11) {
  'driver' => string(9) "pdo_mysql"
  'url' => string(60) "mysql://root:password@127.0.0.1:3306/proj_db?serverVersion=5.7"
  'host' => string(9) "127.0.0.1"
  'port' => string(4) "3306"
  'user' => string(4) "root"
  'password' => string(8) "password"
  'driverOptions' =>
  array(0) {
  }
  'serverVersion' => string(3) "5.7"
  'defaultTableOptions' =>
  array(1) {
    'collate' => string(18) "utf8mb4_unicode_ci"
  }
  'dbname' => string(5) "proj_db"
  'charset' =>
  string(7) "utf8mb4"
}

标签: phpmysqldockerphpunit

解决方案


推荐阅读