Search code examples
cakephptestingcode-coveragecakephp-2.0xdebug

Do we need to test private functions on CakePHP?


I thought private functions should never be tested and only the public interfaces should be.

But then, using XDebug to see the coverage of my function i find out that it decreases as it takes into account the private functions.

What do you think about it? THanks.


Solution

  • I'm a believe that you should test all of your methods, private and protected included. They have logic within them that needs to be tested, despite their visibility to other classes. In order to test protected methods, you often need to create a proxy class that makes the methods public.

    class MyClass {
    
       protected function protected_method() {
         // do stuff
       }
    
    }
    

    In the test case, you would create another class and make its protected methods public, like so

    class TestMyClass extends MyClass {
    
       public function protected_method() {
         return parent::protected_method();
       }
    
    }
    

    Now you can test TestMyClass::protected_method() within the test case.

    This is not the only way to do it. The creator of PHPUnit, Sebastian Bergmann, wrote a blog post about it here: http://sebastian-bergmann.de/archives/881-Testing-Your-Privates.html