使用参数测试抽象类中的方法


Testing methods in abstract classes with arguments

在我的TDD项目中,我试图在一个抽象类中测试一个方法。

abstract class Database_Mapper_Abstract
{
    public function setTable($sTablename){
        return('foo');
    }
}

这是我写简单测试的方式:

public function testCanSetTable(){
        $oMock = $this->getMockForAbstractClass('JCMS_Database_Mapper_Abstract');
        $oMock->expects($this->once())
              ->method('setTable')
              ->with($this->equalTo('foo'))
              ->will($this->returnValue('foo'));
        $this->assertEquals('foo',$oMock->setTable());
    }

当我运行这个测试时,我得到以下错误:

PHPUnit 3.5.13作者:Sebastian Bergmann。

E

时间:1秒,内存:6.75Mb

有1个错误:

1)Database_Mapper_AbstractTest::testCanSetTable缺少的参数1Database_Mapper_Abstract::setTable(),在中调用K: ''examplep''htdocs''tests''library''Database''Mapper''Abstract.php在第15行并定义

K: ''examplep''htdocs''library''Database''Mapper''Abstract.php:4K: ''examplep''htdocs''tests''library''Database''Mapper''Abstract.php:15

失败!测试:1,断言:0,错误:1。

我理解这一点的方式是,它找不到setTable函数的参数。但我用with()方法设置了它。我也试过with('foo')。这对我也没有帮助。

有人有主意吗?

测试抽象类:

对于测试抽象类,您不希望使用"创建行为方法"。

就像这样的getMockForAbstractClass()

<?php
abstract class JCMS_Database_Mapper_Abstract
{
    public function setTable($sTablename){
        return $sTablename."_test";
    }
}
class myTest extends PHPUnit_Framework_TestCase {
    public function testCanSetTable(){
        $oMock = $this->getMockForAbstractClass('JCMS_Database_Mapper_Abstract');
        $this->assertEquals('foo_test', $oMock->setTable('foo'));
    }
}

您只需使用mocking功能来创建该抽象类的实例,并对此进行测试。

这只是写的捷径

class MyDataMapperAbstractTest extends JCMS_Database_Mapper_Abstract {
    // and filling out the methods
}

实际错误:

结果是,你有一个只有一个参数的方法:

public function setTable($sTablename){

但你称之为零配件:

$oMock->setTable()

所以你会从PHP得到一个错误,如果PHP抛出警告,PHPUnit会向你显示一个错误。

再现:

<?php
abstract class JCMS_Database_Mapper_Abstract
{
    public function setTable($sTablename){
        return('foo');
    }
}
class myTest extends PHPUnit_Framework_TestCase {
    public function testCanSetTable(){
        $oMock = $this->getMockForAbstractClass('JCMS_Database_Mapper_Abstract');
        $oMock->expects($this->once())
              ->method('setTable')
              ->with($this->equalTo('foo'))
              ->will($this->returnValue('foo'));
        $this->assertEquals('foo',$oMock->setTable());
    }
}

结果:

 phpunit blub.php
PHPUnit 3.5.13 by Sebastian Bergmann.
E
Time: 0 seconds, Memory: 3.50Mb
There was 1 error:
1) myTest::testCanSetTable
Missing argument 1 for JCMS_Database_Mapper_Abstract::setTable(), called in /home/.../blub.php on line 19 and defined

固定

更改:

$this->assertEquals('foo',$oMock->setTable());

$this->assertEquals('foo',$oMock->setTable('foo'));

那么你就不会得到PHP警告,它应该是:)