【问题标题】:Why is my CakePHP test fixture not working?为什么我的 CakePHP 测试夹具不工作?
【发布时间】:2012-09-24 20:28:47
【问题描述】:

我正在尝试在 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

【问题讨论】:

    标签: cakephp phpunit fixtures


    【解决方案1】:

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

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

    因为它是一个插件;请务必将插件符号与ClassRegistry::init 一起使用,如下所示:

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

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

    【讨论】:

    • 太棒了!你真的很了解你的东西。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-07-21
    • 1970-01-01
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多