DataBase connection problem with PHPUnit and WordPress

I’m trying to run PHPUnit to unittest a WordPress plugin, but the error below keeps showing up.

Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /private/tmp/wordpress/wp-includes/wp-db.php on line 1452

I used WP-CLI to setup the unittests, but also WP-CLI throws a similar error when I try to run it.

I use MAMP to run the database.

I have setup WP-CLI and PHPUnit as phars, that are aliased in ~/.bash-profile, and ran with the default “php” supplied by OS X. Changing this, and running WP-CLI and PHPUnit with the latest PHP version supplied by MAMP fixed WP-CLI(It was running and connecting to the database just fine) but PHPUnit was still throwing the same error.

I have tried editing the wp-config.php file, and setting the host to “:/path/to/mamp/mysql.socket”, “localhost:/path/to/mamp/mysql.socket” and “127.0.0.1”, none of which helped.

I’m totally stuck, and don’t know what to try next.

1 Answer
1

When running the PHPUnit tests, WordPress will load the config from wp-tests-config.php instead of wp-config.php. You need to add your database connection details in wp-tests-config.php.

And if you use MAMP or AMPPS to host your database, you will have to use 127.0.0.1 as DB_HOST instead of localhost. Alternatively use the PHP version supplied by the Solution stack of choice, or set DB_HOST to ‘:/path/to/soulution/stack/mysql.socket’.

Leave a Comment