Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ensure that Laravel 5.5 is running a test?

I have some methods in my app that I check for if (env('APP_DEBUG')) on and return true (or whatever) if we're in debug mode rather than doing a certain DB or API call.

The problem is when I run phpunit, the app is still in debug mode, so it doesn't "really" run the test against the actual code.

Is it possible to check if a test is being run, so I could do if (env('APP_DEBUG') || $testing)? Or is there a better way to handle this case?

like image 353
user101289 Avatar asked Oct 23 '17 02:10

user101289


People also ask

How do I run a PHPUnit test?

How to Run Tests in PHPUnit. You can run all the tests in a directory using the PHPUnit binary installed in your vendor folder. You can also run a single test by providing the path to the test file. You use the --verbose flag to get more information on the test status.

How can I check my Laravel code?

Every Laravel release has the version of the framework as constant in the Application. php file. You can access this constant via the app() helper. If you don't want to create a /test route to get the version, you can use php artisan tinker to get into the tinker REPL and run it from there.


2 Answers

You're looking for App::runningUnitTests().

Remember that you shouldn't use env() outside your configuration files, instead use config('app.debug'). This ensures that your code works with a cached configuration.

It's impossible to answer "is there a better way" without having more details.

like image 146
sisve Avatar answered Nov 07 '22 06:11

sisve


Rather than update your application to check if tests are running, you could disable debug mode in your test environment by updating your phpunit.xml file:

<php>
    <env name="APP_ENV" value="testing"/>
    <env name="CACHE_DRIVER" value="array"/>
    <env name="SESSION_DRIVER" value="array"/>
    <env name="QUEUE_DRIVER" value="sync"/>
    <env name="APP_DEBUG" value="false"/>
</php>

Also, you should not use the env function outside of configuration files. The env function will just return null if you are using the config cache

https://laravel.com/docs/5.5/configuration#configuration-caching

If you execute the config:cache command during your deployment process, you should be sure that you are only calling the env function from within your configuration files.

Use config('app.debug') instead of env('APP_DEBUG').

like image 24
Mathew Tinsley Avatar answered Nov 07 '22 07:11

Mathew Tinsley