NYCPHP Meetup

NYPHP.org

[nycphp-talk] Why do unit tests not inherit?

Robert Stoll rstoll at tutteli.ch
Fri Nov 15 12:57:55 EST 2013



> -----Original Message-----
> From: talk-bounces at lists.nyphp.org [mailto:talk-bounces at lists.nyphp.org] On Behalf Of Gary A. Mort
> Sent: Friday, November 15, 2013 6:23 PM
> To: talk at lists.nyphp.org
> Subject: Re: [nycphp-talk] Why do unit tests not inherit?
> 
> On 11/15/2013 10:58 AM, Robert Stoll wrote:
> > I even think it is ok to have some degree of code duplication in test
> > classes just to make the test case very obvious. Each test case should
> > ideally just cover one aspect (method) and if you start having a lot
> > of test cases for just one method, then you should probably refactor
> > your method.
> 
> One test per method would be a good reason to avoid inheritance. Most open source projects that I've reviewed that
have
> unit tests have one test per class, not per method.
> 
> With one test per class, I find that in real code there is a LOT of code duplication when it comes to child classes. A
> moderately complex hiearchy of classes, with many children coming from one parent, session handling is a good example
> where you may end up with different sessions for many different backends - memcache, file, mysql, mongo, etc.
> 
I am not sure if we talk about the same. Just to avoid misunderstands I am going to outline a little bit more what I
meant. I did not mean that each method of a class has to have its one test class. But each method of a class A should
have an own test method in the test class T. And if the method of class A has branches, let's say one if-statement, then
the ideal case would be that you create two test methods in C which covers both cases. Once for the case that the
if-condition evaluates to true and once to false.
For example:

class A{
    private $_isActive=false;
    function isActive(){
        return $this->_isActive;
    }
    function foo(){
        $this->_isActive=true;
    }

    function bar(){
        if($isActive){
            doesThis();
        } else{
            doesThat();
        }
    }
}

class T extends SomeTestFramework{
    public function testFoo_Standard_IsActiveSetToTrue (){
        // arrange
        // act
        // assert
    }
    public function testBar_IsActiveIsTrue_DoesThis(){}
    public function testBar_IsActiveIsFalse_DoesThat(){}
}

Cheers,
Robert



More information about the talk mailing list