我有一个使用\Zend\Db\TableGateway\TableGateway
来自DI的映射器。我已经嘲笑它进行单元测试。这是测试:
class EMSMapperTest extends PHPUnit_Framework_TestCase
{
public function testFetchAllReturnsAllScheduledBlocks()
{
$resultSet = new ResultSet();
$mockTableGateway = $this->getMock(
'Zend\Db\TableGateway\TableGateway',
array('select','getTable'),
array(),
'',
false
);
$mockTableGateway->expects($this->once())
->method('selectWith')
->with()
->will($this->returnValue($resultSet));
$mockTableGateway->expects($this->once())
->method('getTable')
->with()
->will($this->returnValue('table'));
$emsMapper = new EMSMapper($mockTableGateway);
$this->assertSame($resultSet, $emsMapper->fetchAll());
}
}
正在测试的映射器:
class EMSMapper extends BaseMapper
{
public function fetchAll( $building = null,
$room = null, DateRange $range = null )
{
$select = new Select;
$table = $this->tableGateway->getTable();
$select->from($table);
if(!empty($building))
{
$select->where(array('buildingCode'=>$building));
}
if(!empty($room))
{
$select->where(array("room"=>$room));
}
if(is_array($range))
{
if(!empty($range['start']))
{
$select->where("start >= '{$range['start']}'");
}
if(!empty($range['stop']))
{
$select->where("stop <= '{$range['stop']}'");
}
}
$resultSet = $this->tableGateway->selectWith($select);
$results = array();
foreach($resultSet as $r)
{
$results[] = $r;
}
return $results;
}
}
从TableGateway
getTable()
方法返回字符串后,单元测试说:
There was 1 error:
1) EMSTest\Model\EMSMapperTest::testFetchAllReturnsAllScheduledBlocks
Zend\Db\TableGateway\Exception\RuntimeException:
This table does not have an Adapter setup
如果看起来Select
要求提供给from()
方法的表字符串具有与之关联的适配器。如何提供所需适配器的模拟?
感谢您的帮助!
答案 0 :(得分:0)
您的代码使用selectWith
的实际代码。这会调用initialize
方法来引发错误。
将模拟代码更改为:
$mockTableGateway = $this->getMock(
'Zend\Db\TableGateway\TableGateway',
array('selectWith','getTable'),
array(),
'',
false
);
这应该正确配置你的模拟。
http://phpunit.de/manual/current/en/test-doubles.html
从手册:
当提供第二个(可选)参数时,只有名称在数组中的方法将替换为可配置的测试double。其他方法的行为不会改变。提供NULL作为参数意味着不会替换任何方法。
所以你在正确的方法上设置了期望值,但是用模拟替换了错误的方法,所以真正的代码正在被执行。