用PHPUnit测试抽象类的方法 [英] Test methods of Abstract Class with PHPUnit

查看:70
本文介绍了用PHPUnit测试抽象类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,其中包含要测试的通用方法,因此不必在扩展该类的每个类中继续对其进行测试.

I have an abstract class that has common methods in it, that I wish to test, so I do not have to keep testing them in each class that extends this class.

abstract class Class1 implements iClass1
{
    const VALUE = 'A';
    private $Return;    
    public function __construct($Field = NULL)
    {
        if( ! is_null($Field) )
            $this->SetField($Field);
    }
    public function GetField()
    {
        return $this->Return;
    }
    public function SetField($Field)
    {
        if (strlen($Field) != 3)
        throw new CLASS1_EXCEPTION('Field "' . $Field . '" must be 3 digits.');

    $this->Return = $FieldCode;
    }
    abstract function CalculateData();
}

我想创建一个基本的测试用例,然后将对构造函数,GetField和其他函数进行测试,然后我的其他测试文件就可以对抽象函数进行测试了.

I want to create the basic test case then that will test the constructor, and the GetField and other functions, then my other test files can test the abstract functions.

我希望能够测试const没有改变,该字段引发异常等...

I want to be able to test the const has not changed, the field throws the exception etc...

测试:

class TEST_CLASS1 extends PHPUnit_Framework_TestCase
{
    protected function setUp()
    {
        require_once('CLASS1.php');
    }
    public function testConstants()
    {
        $this->assertEquals(CLASS1, 'A');
    }

    /* @expectedException CLASS1_EXCEPTION
    public function testLargeFieldException()
    {
        $class1 = new CLASS1('ABCD');
        $class1 = new CLASS1();
        $class1->SetField('ABCD');
    }
}

由于无法创建CLASS1对象,因为它是一个抽象类,该如何创建测试?

How do I create the tests since I can not create the CLASS1 object as it is an abstract class?

推荐答案

一种选择是创建

TestableClass1 extends Class1 {
     public function CalculateData() {}
}

并使用该类进行测试.

另一个选择是做几乎相同的事情,但是使用phpunit提供的API:

The other option is to do pretty much the same but use an API phpunit provides you with:

为此,请参见示例示例10.13:测试 -doubles.html#test-doubles.mock-objects"rel =" noreferrer> phpunit documentation :

For this see the sample Example 10.13: Testing the concrete methods of an abstract class of the phpunit documentation:

abstract class AbstractClass
{
    public function concreteMethod()
    {
        return 5;
    }

    public abstract function abstractMethod();
}

class AbstractClassTest extends PHPUnit_Framework_TestCase
{
    public function testConcreteMethod()
    {
        $sut = $this->getMockForAbstractClass('AbstractClass');
        $this->assertSame(5, $sut->concreteMethod());
    }
}

这篇关于用PHPUnit测试抽象类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆