Tuesday, 21 April 2015

PHP: unit testing private methods... PHP 5.5 version

G'day:
The Central Line isn't running at the moment and the buses are all shagged due to everyone wanting now to catch one, so I've given up trying to get to work and gone home until things settle down a bit. Not wanting to be completely useless to my employers, I've decided to solve an issue I created yesterday by recommending using some PHP 5.6-only code on out 5.5 environment. Duh.

Over the weekend I wrote up an article "PHP: unit testing private methods (a bit of reflection)", which did what it suggests: uses reflection to enable testing private methods. The key function is thus:

private function executePrivateMethod($object, $method, $arguments){
    $reflectedMethod = new \ReflectionMethod($object, $method);
    $reflectedMethod->setAccessible(true);

    $result = $reflectedMethod->invoke($object, ...$arguments);
    return $result;        
}

Unfortunately this uses the ellipsis operator (which I have an article about: PHP: new to me: the ... "operator"), which is only supported from PHP v 5.6.

However the issue was easily solved by using a different reflection method to call the function:

private function executePrivateMethod($object, $method, $arguments){
    $reflectedMethod = new \ReflectionMethod($object, $method);
    $reflectedMethod->setAccessible(true);

    $result = $reflectedMethod->invokeArgs($object, $arguments);
    return $result;        
}

invokeArgs() takes the method's arguments as an array, rather than individual args. Sorted.


The other thing to note here is how easy it was to run my tests on PHP 5.5 instead of the usual 5.6. I simply downloaded and unzipped 5.5, then adjusted my phpunit.bat file thus:

@ECHO OFF
SET BIN_TARGET=%~dp0/../phpunit/phpunit/phpunit
C:\apps\php\php-5.5.24-Win32-VC11-x64\php.exe "%BIN_TARGET%" %*

Simply changing the PHP path to be the 5.5 directory instead of letting it pick up PHP's location from the PATH environment variable.

I saved that as phpunit55.bat so I can run the tests with either version. Simple.

Anyway, I better go see what's happening about the Tubes. Work does expect me to show up at some point.

Righto.

--
Adam