3

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?

1
  • What do you mean ignores? If these are set by Apache and you're running your tests through something else they're not going to exist. Commented Aug 14, 2016 at 21:40

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.