Unit Testing Private Code
After doing various unit testing for VDE, I’ve encountered a quite annoying flaw with PHP unit testing in general. You can’t test private or protected functions, since they are being called publicly from the test function.
Since in most cases you are testing a class file with only classes in it, I decided to try a few ways to modify the script to remove the visibility…
I first toyed with some horrible ideas, like using a modified copy of the file for testing, or editing the file at runtime (a duplicate, and then removing it after). Finally I decided to go with the function with the ugliest face in PHP - eval. This was the simplest solution, as I just load the file contents into memory, do some simple replacements, and then evaluate the string and voila! my classes are now in memory without any annoying visibility restrictions.
Here is the code I used to set this up,
-
<?php
-
-
class VDE_Watch_Test extends UnitTestCase
-
{
-
private $vb;
-
private $vde;
-
-
public function __construct()
-
{
-
$this->vb = $GLOBALS[‘vbulletin’];
-
}
-
-
// tests
-
}
-
-
function load_file_without_visbility($filename)
-
{
-
‘/(public|protected|private) \$/’,
-
‘/(public|protected|private) function/’,
-
),
-
‘var /* $1 */ $’,
-
‘/* $1 */ function’
-
),
-
);
-
-
-
}
-
-
?>
It’s not perfect, but it would be easy enough to fix any minor gotchas which I’ve yet to encounter.



No Responses to “Unit Testing Private Code”
Please Wait
Leave a Reply