phpunitconfiglaravel-5.7

How do you detect which database is being used during a phpunit test?


We have been having issues with local databases getting deleted while performing phpunit tests due to mistakes made in config files. I want write a function that will check to see which database is being connected to right before a test is run, and exiting if the correct one is not being used. How do you detect which database is being used during a phpunit test? One situation I want to catch is when a setting has been updated, but not cached (the files look correct, but the wrong database is being used.)

I've tried env() and config() and neither give me what I am looking for.

$dbconnect = DB::connection()->getPDO();
$dbname = DB::connection()->getDatabaseName();

Throws an error.

I can open the physical .env and env.testing file and find the settings, but this does not work if the setting have not been cached correctly.


Solution

  • Selecting the wrong database during a phpunit test can be a disaster. Doing this can destroy your real data. Here's a simple solution: write database query early in the setUp() function that looks for real data or test data (the user table is a good target.)

    Example:

    DB::table('users')->get();

    If real users are found, then you know you have the wrong database selected, and you can exit(). Also, you will want to precede this query with a check to make sure that the database in not empty. Otherwise, the table() function will return an error. If the database is empty, then you probably don't have a database with useful data selected.

    Example:

    DB::select('SHOW TABLES');