1

我正在尝试使用 Doctrine 2 ORM 设置我的 PHPUnit 测试。但是,我遇到了一些奇怪的问题,我只能假设是某种缓存(在 Doctrine 结束时),我无法弄清楚如何克服。这就是我所拥有的:

设置功能:

public function setUp() 
{
    $front = Zend_Controller_Front::getInstance();
    $bootstrap = $front->getParam("bootstrap");

    if(!$boostrap) {
        $application = Zend_Registry::get("application");
        $bootstrap = $application->getBootstrap();
    }
    $bootstrap->bootstrap('doctrine');

    $this->em   = $bootstrap->getResource('doctrine');
    $tool       = new \Doctrine\ORM\Tools\SchemaTool($this->em);
    $classes    = $this->em->getMetaDataFactory()->getAllMetaData();

    $tool->dropSchema($classes);
    $tool->createSchema($classes);

    parent::setUp();
}

这基本上旨在为每个测试重置教义实例。我还没有 tearDown() 函数,因为目前,它负责重置模式,如图所示。我应该在这里提到我正在使用 SQLite。

我正在尝试运行的一个类中有两个测试,没有依赖关系。第一个测试插入如下记录:

$value = 5;
$model = new Model();
$model->setUserId($rater->getId());
$model->setValue($value);

$this->em->persist($model);
$this->em->flush();

到现在为止还挺好。我在数据库中有一条值为 5 的新记录。

进入下一个测试。这次我想跑:

$value = 3;
$model = new Model();
$model->setUserId($rater->getId());
$model->setValue($value);

$this->em->persist($model);
$this->em->flush();

Dumping all records from the relevant table gives me one result; a record with a value of 5 again. In other words, the second test is taking the $value from the first test. I've double checked by dumping all records at the start of the second test and this returns nothing. It seems there are some caching issues in Doctrine somewhere that I'm not aware of.

I've tried clearing various caches that I'm aware Doctrine can potentially make sure of, such as:

$cacheDriver = new \Doctrine\Common\Cache\XcacheCache();
$cacheDriver->deleteAll();

Can anybody suggest anything else I can try? Or is there some errant code somewhere in the way I have implemented Doctrine.

Thanks

4

1 回答 1

2

So I'm not entirely sure where or what the issue was, but it seems that Doctrine must have been caching somewhere down the line. After all, I ensured that my object had the correct value post-persist but pre-flush. Post-flush it suddenly had a different value than expected.

Anyhow, to fix the issue I added the following line:

$this->em->clear();

just after getting the doctrine resource from my Bootstrap. This ensures that all managed entities are completely cleared from the Entity Manager before dropping and re-creating the schema.

于 2012-08-07T14:08:19.567 回答