How to Determine if PHPUnit Tests are Running?

痴心易碎 提交于 2020-07-17 07:14:44

问题


I currently have a problem that I have to work around in legacy code to get our interaction with a PHP Extension to work properly (Singleton Testing Question).

As such, I do not want to execute this code when running our normal production code with the application. Therefore, I need to check in regular PHP code if the code being executed is being executed as part of a test or not.

Any suggestions on how to determine this? I thought about a defined variable tied to the presence of the test files themselves (we do not ship the tests to customers) but our developers need the Extension to work normally, while the CI server needs to run the tests.

Would a Global set in the PHPUnit.xml file be recommended? Other thoughts?


回答1:


Define a constant in your PHPUnit bootstrap.php file. This is executed before loading or running any tests. This shouldn't impact developers running the application normally--just the unit tests.




回答2:


An alternative approach is to set a constant in the PHP section of your phpunit.xml.*:

<php>
   <const name="PHPUNIT_YOURAPPLICATION_TESTSUITE" value="true"/>
</php>

In your PHP application, you might then use the following check:

if (defined('PHPUNIT_YOURAPPLICATION_TESTSUITE') && PHPUNIT_YOURAPPLICATION_TESTSUITE)
{ 
    echo 'TestSuite running!';
}



回答3:


If you're using Laravel than use App::runningUnitTests()




回答4:


You could check the $argv different ways.

if(PHP_SAPI == 'cli') {

    if(strpos($_SERVER['argv'][0], 'phpunit') !== FALSE) { ... }
    // or
    if($_SERVER['argv'][0] == '/usr/bin/phpunit') { ... }

}



回答5:


Use PHPUnit Constants

You can either define constant, but that requires your work, no typos and it's not generic. How to do it better?

PHPUnit defines 2 constants by itself:

if (! defined('PHPUNIT_COMPOSER_INSTALL') && ! defined('__PHPUNIT_PHAR__')) {
    // is not PHPUnit run
    return;
}

// is PHPUnit


来源:https://stackoverflow.com/questions/10253240/how-to-determine-if-phpunit-tests-are-running

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!