Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test statements which depends on specific PHP version with PHPUnit?

I have a construct 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 test this code with PHPUnit to achieve a 100% code coverage if the existence of the function foo depends on the installed PHP version (for this example i assume that the function exists, otherwise a code coverage of 100% is impossible). Is there a way to disable/enable PHP functions at runtime?

Any ideas how to solve it?

EDIT:

i have found a solution: the Advanced PHP debugger / PECL extension provide a function *rename_function* for this purposes.

bool rename_function ( string $original_name , string $new_name )

Renames a orig_name to new_name in the global function table. Useful for temporarily overriding built-in functions.

like image 440
nico Avatar asked Dec 22 '12 18:12

nico


2 Answers

You can define a simulation of foo() in your test method. 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 may defined into another method or function. Although they are defined in the method they are globally available.

Using the pecl extension is not required. Further it potentially pollutes the test execution environment and at least adds unneeded requirements.

Furthermore note that PHPUnit as from version 3.6 supports the annotations @codeCoverageIgnore, @codeCoverageIgnoreStart, @codeCoverageIgnoreEnd to can be used to exclude classes, methods or parts of code from coverage analysis.

like image 112
hek2mgl Avatar answered Nov 13 '22 11:11

hek2mgl


Well, in PHP 5.3 and higher 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's fallback mechanism. In short, when it encounters a function it first checks if the function exists in the current namespace. If not, it falls back to the global namespace.

like image 42
zafarkhaja Avatar answered Nov 13 '22 11:11

zafarkhaja