Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit ignores Apache environment variables

I'm using Codeception, which leverages PHPUnit as its unit testing framework, and have a number of unit tests

I recently updated my database connection using connection info stored in the php configuration file (rather than hard-coded).

$host = getenv('RDS_HOST');
$user = getenv('RDS_USER');
$password = getenv('RDS_PASSWORD');
$schema = getenv('RDS_SCHEMA');

$mysqli = new \mysqli($host, $user, $password, $schema);

My app works just fine after these changes.

Problem is, many of my unit tests are now broken, running unit tests results in the error message:

[PHPUnit_Framework_Exception] mysqli::mysqli(): (HY000/2002): No such file or directory

I created unit tests just to see if PHPUnit will read my environment variables. It appears that it does not. It seems that PHPUnit is ignoring my environment variables.

How can I get PHPUnit/Codeception to recognize and use Apache environment variables?

like image 921
devon Avatar asked Jun 04 '26 06:06

devon


1 Answers

PHPUnit is run via the cli, the web application is run via apache, which is why one works and the other doesn't.

For example, if you're running your tests on a Linux system from the command line you could export environment variables.

$ export RDS_HOST=host; export RDS_USER=user; and so on... vendor/bin/phpunit 

Those environment variables will then be available in php via getenv. Whereas in apache, for example, you might set them in a vitual host, so that when apache runs, those environment variables are available to PHP.

There are so many ways handle this, I don't know of any definitive solution. It depends on the application scope and its needs. vlucas/phpdotenv is the only package I can think of off the top of head that I think helps solves this problem for some use-cases.

Dive deeper: How Laravel Solves It

like image 54
Gerard Roche Avatar answered Jun 05 '26 20:06

Gerard Roche



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!