Testing

Testing abstract classes without creating child object

Max Hutschenreiter -

Abstract classes can contain concrete methods that should be tested. One way to do it would be to create a child class of the abstract class and test that one.

Letโ€™s imagine that we have an abstract class Person
public function __construct($name){
    $this->name = $name;
}
 
abstract protected function getTitle();
 
public function getTitleAndName()
{
    return $this->getTitle() . ' '. $this->name;
}
While we are testing this class, usually we would create for example class Doctor which extends Person
class Doctor extends Person
{
    protected function getTitle(){
        return 'Dr.';
    }
}
so the test would look like:
public function testTitleAndNameOutput(){
    $doctor = new Doctor('Danijel');
    $this->assertEquals('Dr. Danijel', $doctor->getTitleAndName());
}
However, thereโ€™s a more elegant way to test abstract class without creating unnecessary child object:
public function testTitleAndNameOutput(){
 
    $mock = $this->getMockBuilder(Person::class)
                 ->setConstructorArgs(['Danijel'])
                 ->getMockForAbstractClass();
 
    $mock->method('getTitle')
         ->willReturn('Dr.');
 
    $this->assertEquals('Dr. Danijel', $mock->getTitleAndName());
}
More info about mocking abstract classes and traits can be found here.

Tags: testing · phpUnit · abstract class test · testing class

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • Happy birthday ๐ŸŽ๐ŸŽˆ๐ŸŽ‚ Filip - #

  • Another day another #mandarinacakeshop ๐ŸŽ‚ ๐Ÿ˜€ - #

  • Happy Birthday Ognjen! And marry Christmas to all other ๐ŸŽ„#notacakeshop - #

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan ๐Ÿฅ‚ - #

  • #happybirthday Lidija ๐Ÿพ - #

  • Say hi ๐Ÿ‘‹ to our newest team member โ˜•๏ธ - #

  • #bithday #cake ๐Ÿ˜ป - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday ๐ŸŽ‚ Miloลก - #

  • Happy Birthday ๐ŸŽ‚Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday ๐ŸŽ‚ Ognjen - #

  • Wish you all a merry Christmas ๐ŸŽ„๐ŸŽ - #

See more!

© 2024 42coders All rights reserved.