EU Cookie Consent

To use this Website we are using Cookies and collecting some Data. To be compliant with the EU GDPR we give you to choose if you allow us to use certain Cookies and to collect some Data.

Essential Data

The Essential Data is needed to run the Site you are visiting technically. You can not deactivate them.

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 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 🎄🎁 - #

  • #happybirthday Luka! - #

  • https://communian.com Triff dich mit Menschen aus deiner Umgebung die deine Interessen teilen :) Wir sind gerade live gegangen und freuen uns über jede neue Community die zu uns kommt ❤️ - #

© 2021 42coders All rights reserved.