我正在尝试使用 phpunit 为使用 Doctrine 2 的模型编写单元测试。我想模拟 Doctrine 实体,但我真的不知道如何做到这一点。谁能向我解释我需要如何做到这一点?我正在使用 Zend 框架。
需要测试的模型
class Country extends App_Model
{
public function findById($id)
{
try {
return $this->_em->find('Entities\Country', $id);
} catch (\Doctrine\ORM\ORMException $e) {
return NULL;
}
}
public function findByIso($iso)
{
try {
return $this->_em->getRepository('Entities\Country')->findOneByIso($iso);
} catch (\Doctrine\ORM\ORMException $e) {
return NULL;
}
}
}
Bootstrap.php
protected function _initDoctrine()
{
Some configuration of doctrine
...
// Create EntityManager
$em = EntityManager::create($connectionOptions, $dcConf);
Zend_Registry::set('EntityManager', $em);
}
扩展模型
class App_Model
{
// Doctrine 2.0 entity manager
protected $_em;
public function __construct()
{
$this->_em = Zend_Registry::get('EntityManager');
}
}
最佳答案
我为使用 Doctrine 的单元测试提供了以下 setUp 和tearDown 函数。它使您能够在不实际接触数据库的情况下进行 Doctrine 调用:
public function setUp()
{
$this->em = $this->getMock('EntityManager', array('persist', 'flush'));
$this->em
->expects($this->any())
->method('persist')
->will($this->returnValue(true));
$this->em
->expects($this->any())
->method('flush')
->will($this->returnValue(true));
$this->doctrine = $this->getMock('Doctrine', array('getEntityManager'));
$this->doctrine
->expects($this->any())
->method('getEntityManager')
->will($this->returnValue($this->em));
}
public function tearDown()
{
$this->doctrine = null;
$this->em = null;
}
然后,您可以在需要时使用 $this->doctrine
(甚至)$this->em
。如果您想使用 remove
或 getRepository
,则需要添加更多方法定义。
关于php - 如何创建一个 Doctrine 实体的模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3575902/