Re: any thoughts on self-testing classes?
| From: | Dmitri Snytkine | Date: | Sat, 28 Mar 2009 15:53:13 +0000 |
| Subject: | Re: any thoughts on self-testing classes? | ||
| References: | 1 2 | Groups: | php.pear.dev |
| Request: | Send a blank email to pear-dev+get-51688@lists.php.net to get a copy of this message | ||
Very good answer, thank you.
Sorry, but what is PPP?
On Sat, Mar 28, 2009 at 11:42 AM, Greg Beaver <greg@chiaraquartet.net>wrote:
> Dmitri Snytkine wrote:
> > Just wondering what experienced developers think about self-testing
> classes,
> > - classes that include their own test() method inside the class which
> runs
> > test suite and tests all methods.
> >
> > This is one way to have access to private methods while running tests.
> >
> > Any of you using this approach in your development?
>
> Hi Dmitri,
>
> I would not consider this approach simply because it mixes purposes, and
> introduces all kinds of weird ways to screw up the intended normal
> operation of the class.
>
> I would also suggest that this is not the way to solve the problem of
> accessing private methods.
>
> After having used PPP for a couple of years in PHP now, I can report
> that the best solution is to avoid the word "private" unless you really
> mean "final" - as in the entire operation of the class would be
> jeopardized if any change is ever made to the operation of a method. In
> this case, slapping "private" in front of it is a very good idea.
>
> For most situations, once you switch "private" to "protected" you get
> the best of both worlds. It becomes impossible to call a method from
> outside the class hierarchy, but you can still extend the class and
> override the method, which allows testing to work simply via a mock.
> For instance:
>
> class MyMock extends Fancy_Class
> {
> public function whatever()
> {
> return parent::whatever();
> }
> }
>
> This way, your test can simply instantiate MyMock and call whatever()
> directly to test it.
>
> There are other problems with including test() methods inside the class,
> one of which is that the memory usage of your class and load time
> increases even with an opcode cache, all with deadweight code that is
> never executed in normal operation.
>
> This is all another way of saying that if you design your code to be
> testable, then you won't need to do anything awkward in the code itself
> in order to test it.
>
> Greg
>