Refactored

Unit Testing Private Code

by Adrian on Feb.17, 2008, under Debugging and Testing

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,

Code: (Plain Text)
  1. <?php
  2.  
  3. class VDE_Watch_Test extends UnitTestCase
  4. {
  5.     private $vb;
  6.     private $vde;
  7.  
  8.     public function __construct()
  9.     {
  10.         $this->vb = $GLOBALS[‘vbulletin’];
  11.         load_file_without_visbility(DIR . ‘/includes/class_vde_watch.php’);
  12.         load_file_without_visbility(DIR . ‘/includes/class_vde_watch_template.php’);
  13.     }
  14.  
  15.     // tests
  16. }
  17.  
  18. function load_file_without_visbility($filename)
  19. {
  20.     $php = preg_replace(
  21.         array(
  22.             ‘/(public|protected|private) \$/’,
  23.             ‘/(public|protected|private) function/’,
  24.         ),
  25.         array(
  26.             ‘var /* $1 */ $’,
  27.             ‘/* $1 */ function’
  28.         ),
  29.         file_get_contents($filename)
  30.     );
  31.  
  32.     $php = str_replace( array(‘<?php’, ‘?>’), array(,), $php);
  33.  
  34.     eval($php);
  35. }
  36.  
  37. ?>

It’s not perfect, but it would be easy enough to fix any minor gotchas which I’ve yet to encounter.

:, ,
No comments for this entry yet...

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...