4

Right now I have configured this environment variable in my phpunit.xml to connect to a Drupal database in a SQLite file:

<env name="SIMPLETEST_DB" value="sqlite://localhost//Users/jepster/Dev/my-project/project/docroot/sites/default/files/db.sqlite"/>

This works fine. But can I also connect to a second database like I am doing in the settings.php?

$databases['second-database']['default'] = array(
  'database' => 'second-database',
  'username' => 'second-database',
  'password' => 'second-database',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);

Currently my Kernel Base Test fails with the following error:

The specified database connection is not defined: second-database

That's because I want to connect to my database from a service constructor:

  public function __construct() {
    $this->database = Database::getConnection('default','second-database');
  }

I have been digging in the Drupal core Kernel Base Tests ("core" folder), but I could not find a way there.

5

I have figured it out. The setUp() method in my Kernel Base Test must look like that:

/**
 * {@inheritdoc}
 */
protected function setUp() {
    parent::setUp();

    $databases['second-database']['default'] = array(
        'database' => 'second-database',
        'username' => 'second-database',
        'password' => 'second-database',
        'prefix' => '',
        'host' => 'localhost',
        'port' => '3306',
        'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
        'driver' => 'mysql',
    );
    Database::setMultipleConnectionInfo(
        $databases
    );
}
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.