[TYPO3-dev] Unit tests and method visibility

Xavier Perseguers typo3 at perseguers.ch
Sun Jul 5 23:07:13 CEST 2009


Hi Francois,

> I'm trying to design my first unit tests (wow!) and I'm faced with a 
> problem. I want to test the result of a method which should logically be 
> "protected". But since the test is outside the scope of the class that 
> method belongs to, I get a fatal error trying to call it.
> 
> Is there a way to design unit tests for protected (or private) methods?

In C# this is done through an accessor. A special dynamically-generated 
class that changes your protected methods as public methods for 
test-purpose. You test then this class instead of the original one.

But most important is that normally what you want to test is the 
signature of your class, meaning the public methods (which in turn will 
probably use your protected and private methods, otherwise you wouldn't 
have written them).

The inner working of your class is not important as a user but the 
public methods should do what they are intended to.

In your case, if you really want to unit-test them, I guess you should 
start subclassing your classes with something like this:

class Foo {
     protected function doSomething() {
         // your code
     }
}

// In test files
class SubFoo extends Foo {
     public function exposedDoSomething() {
         return $this->doSomething();
     }
}

-- 
Xavier Perseguers
http://xavier.perseguers.ch/en

One contribution a day keeps the fork away




More information about the TYPO3-dev mailing list