Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test an abstract class with PHPunit?

Lets assume I have a file at /var/www/project/calculator.class.php

and here is the class

namespace App/Module/Calculator; 

abstract class calculator{

 static property $add; 

 static property $result; 

 function add($val_a, $val_b){
    return $a + $b; 
 }

}

I would like to create a test case, for the above class, but it seems impossible to test it. I am stuck at the very basic stage.

require '/var/www/project/calculator.class.php';

 class CalculatorTest extends \PHPUnit_Framework_TestCase {

    public function testAbstactDatabaseClassExists()
    {

       $this->assertEquals(is_object('Database'), 1);
      $this->assertEquals(true, in_array('Calculator', get_declared_classes()));

    }

 }

No matter what I do, there does not seem to be a way to test, the class and it's contents.

Anyone has any idea?

like image 734
spartak Avatar asked Jun 07 '14 16:06

spartak


1 Answers

When testing abstract classes, you may use the Mock features of PHPUnit. An example for the add method would be as following:

public function testAdd() {
    /* @var $calculator \App\Module\Calculator\calculator|\PHPUnit_Framework_MockObject_MockObject */
    $calculator = $this
        ->getMockBuilder('App\Module\Calculator\calculator')
        ->getMockForAbstractClass();

    $result = $calculator->add(13, 29);
    $this->assertEquals(42, $result);
}

For further information about Mocking, please refer to the PHPUnit manual.

like image 168
BluePsyduck Avatar answered Oct 24 '22 06:10

BluePsyduck