如何创建一个原则实体的模拟对象? [英] How to create a mock object of a doctrine entity?
问题描述
我试图用phpunit编写一个使用原则2的模型的单元测试。我想嘲笑原则实体,但我真的不知道如何做这个。任何人都可以向我解释我需要做什么?我正在使用Zend Framework。
I'm trying to write a unit test with phpunit for a model that uses doctrine 2. I want to mock the doctrine entities but I really don't have a clue of how to do this. Can anyone explain to me how I need to do this? I'm using Zend Framework.
需要测试的模型
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');
}
}
推荐答案
2实体应该像任何老类一样对待。您可以像PHPUnit中的任何其他对象一样模拟它们。
Doctrine 2 Entities should be treated like any old class. You can mock them just like any other object in PHPUnit.
$mockCountry = $this->getMock('Country');
正如@beberlei所说,你在Entity类里面使用EntityManager,它创建了一个粘性问题,打败了教义2的主要宗旨之一,即实体不关心自己的坚持。这些查找方法确实属于存储库类。
As @beberlei noted, you are using the EntityManager inside the Entity class itself, which creates a number of sticky problems, and defeats one of the major purposes of Doctrine 2, which is that Entity's aren't concerned with their own persistance. Those 'find' methods really belong in a repository class.
这篇关于如何创建一个原则实体的模拟对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!