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.