I am running a test that extends a BrowserTestBase and indicated a custom module as a dependency. The module has a mymodule_module_preinstal()
that is supposed to perform a DB query using Drupal::database()
.
After wasting some time on figuring out why it does not work I realized that the query is run against the main databse of the installation, not that which I had set up in phpunit.xml.
That's really confusing - why is it working like that and why on earth would I want to work with the main database while running a test which is supposed to be run in an isolated database?
And, most importantly, how do I run the query against the test database?
Excerpt from documentation:
It's terribly important to realize that each test runs in a completely new Drupal instance, which is created from scratch for the test. In other words, none of your configuration and none of your users exists!
Here's code of my test:
class FormTest extends BrowserTestBase
{
public static $modules = ['mymodule', 'mymodule2'];
public function testFormPage()
{
$response = $this->drupalGet('/mymodule/register');
}
}
I've also copied phpunit.xml.dist to phpunit.xml and set up this line:
<env name="SIMPLETEST_DB" value="mysql://mydb_tests:password@localhost/mydb_tests"/>
I run my test like this:
cd core
phpunit ../modules/mymodule/tests/src/MyTest.php
I have installed the version of phpunit from core/composer.json globally.
The preinstall hook looks like this:
/**
* Module preinstall hook
* @param $module_name
*/
function mymodule_module_preinstall($module_name)
{
var_dump($module_name);
print_r(Drupal::database()->query("SHOW TABLES")->fetchAll());
exit();
}