php - 如何创建一个 Doctrine 实体的模拟对象?

标签 php unit-testing zend-framework doctrine phpunit

我正在尝试使用 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。如果您想使用 removegetRepository,则需要添加更多方法定义。

关于php - 如何创建一个 Doctrine 实体的模拟对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3575902/

相关文章:

php - 向mysql插入数据不起作用

c# - 用于测试调用异步方法的 ICommand 的模式

javascript - AngularJS:带有从服务返回的 Promise 的单元测试指令

php - 使用 PHP 写入 Google Docs 电子表格

zend-framework - Zend 框架装饰器问题

php - 从两个表中查找并删除一条记录? MySQL PHP

php - 将 php 文件加载到布局模板中?

unit-testing - 如何防止从使用dart中的ExpectAsync的单元测试进行?

php - Zend Framework 路由 : . html 扩展

php - 从 mysql 表加载的 php 代码不会在输出页面上解释