为什么我的CakePHP测试夹具无法正常工作?

时间:2012-10-03 20:36:27

标签: cakephp phpunit fixtures

我正在尝试在CakePHP应用程序中测试插件模型。该模型使用一个名为'cron_jobs'的表,我已经为此设置了这个夹具:

class CronJobFixture extends CakeTestFixture
{
    public $import = array('table' => 'cron_jobs');
}

我的测试类效果很好,看起来像这样:

<?php

App::uses('CronJob', 'Cron.Model');

class CronJobTest extends CakeTestCase
{

    public $fixtures = array('plugin.cron.CronJob');

    public function setUp()
    {
        parent::setUp();
        $this->CronJob = new CronJob();
    }

    public function testCollectFailsOnMissingComponent()
    {
        $this->setExpectedException('InvalidArgumentException');
        $this->CronJob->collect(null);
    }

    public function testCollectSilentOnMissingComponent()
    {
        $result = $this->CronJob->collect('SomeNonExistingComponent');
        $this->assertEquals(null, $result);
    }

    // Some more tests that will need the fixture ....
}

如果我然后通过替换

更改测试设置
$this->CronJob = new CronJob();

$this->CronJob = ClassRegistry::init("CronJob");

加载灯具,我收到此错误:

  

CronJobTest :: testCollectSilentOnMissingComponent PDOException:   SQLSTATE [42000]:语法错误或访问冲突:1064您有   SQL语法错误;查看与您的手册相对应的手册   MySQL服务器版本,用于在“收集”附近使用正确的语法   第1行

CronJob类中的任何内容都无法生成错误,因为两个测试所涵盖的代码不会访问数据库。我确信我的测试数据库配置正确,因为如果我对测试数据库配置进行了更改,则会出现数据库连接错误。

我正在使用CakePHP 2.2.1,PHPUnit 3.6.12,PHP 5.4

1 个答案:

答案 0 :(得分:2)

Fixtures更喜欢小写的下划线约定。这样做:

public $fixtures = array('plugin.cron.cron_job');

因为它是一个插件;请务必使用ClassRegistry::init这样的插件表示法:

$this->CronJob = ClassRegistry::init('Cron.CronJob');

发生该错误是因为CakePHP在没有CronJob方法的情况下延迟加载非插件collect()模型。

相关问题