How to check statements that depend on a particular version of PHP with PHPUnit?

I have a design like this:

class Foo { public function doFoo($value = '') { if (function_exists('foo')) { return foo($value); } // if php version does not support foo() // ... } } 

How can I check this code with PHPUnit to achieve 100% coverage of the code if the existence of the foo function depends on the installed version of PHP (for this example, I assume that this function exists, otherwise code coverage is 100% impossible). Is there any way to disable / enable PHP functions at runtime?

Any ideas how to solve it?

EDIT:

I found a solution: the advanced PHP debugger / PECL extension provides the * rename_function * function for this purpose.

bool rename_function (line $ original_name, line $ new_name)

Renames the name orig_name to new_name in the global function table. It is useful to temporarily override the built-in functions.

+6
source share
2 answers

In the test method, you can define the simulation foo() . Do something like this:

 <?php /** * Your test method */ public function testSomething () { // if the function not exists, create a simulation if(!function_exists('foo')) { function foo() { return $aValue; } } // your test code ... } 

This works because a function can be defined in another method or function. Although they are defined in the method, they are available worldwide.

Using the pecl extension is not required. In addition, it potentially pollutes the test execution environment and at least adds unnecessary requirements.

In addition, note that PHPUnit since version 3.6 supports annotations @codeCoverageIgnore , @codeCoverageIgnoreStart , @codeCoverageIgnoreEnd , which can be used to exclude classes, methods, or portions of code from coverage analysis.

+3
source

Well, in PHP 5.3 and later, you can override the behavior of any PHP function.

Look at this

 namespace Test { function function_exists($function) { return false; } var_dump(function_exists('var_dump')); // bool(false) } 

This is possible due to the PHP backup mechanism. In short, when it encounters a function, it first checks to see if the function exists in the current namespace. If not, it reverts to the global namespace.

+1
source

All Articles