简体   繁体   中英

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?

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 .

Simple way - create child class from calculator, and use child in test (but it is not good practice):

class CalculatorChildForTest extends calculator
{
}
// your test here use CalculatorChildForTest
class CalculatorTest extends \PHPUnit_Framework_TestCase {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM