【问题标题】:cakephp unit testing models, fixtures problemcakephp 单元测试模型,夹具问题
【发布时间】:2010-12-14 02:38:29
【问题描述】:

所以我正在使用 CakePHP v1.2.5。在我当前的项目中,我决定在编写功能代码时开始编写测试(耶 TDD)。我在加载夹具时遇到了问题。

为了帮助完成这个过程,我将描述我的代码(现在真的很简单)。我的模型是这样定义的

// app/models/newsitem.php
<?php
class NewsItem extends AppModel
{
  var $name='NewsItem';
}
?>

// app/tests/fixtures/newsitem_fixture.php
<?php

class NewsItemFixture extends CakeTestFixture 
{
    var $name = 'NewsItem';
    var $import = 'NewsItem';

    var $records = array(
        array('id' => '1', 'title' => 'News Item 1', 'body' => 'This is the first piece of news', 'created' => '2007-03-18 10:39:23', 'modified' => '2007-03-18 10:41:31'),
        array('id' => '2', 'title' => 'News 2', 'body' => 'This is some other piece of news', 'created' => '2009-05-04 9:00:00', 'modified' => '2009-05-05 12:34:56')
    );
}

?>

// app/tests/models/newsitem.test.php
<?php
App::Import('Model', 'NewsItem');

class NewsItemTestCase extends CakeTestCase
{
    var $fixtures = array('app.newsitem');

    function setUp()
    {
        $this->NewsItem =& ClassRegistry::init('NewsItem');
    }

    function testFindAll()
    {
        $results = $this->NewsItem->findAll();
        $expected = array(
            array('NewsItem' => array('id' => '1', 'title' => 'News Item 1', 'body' => 'This is the first piece of news', 'created' => '2007-03-18 10:39:23', 'modified' => '2007-03-18 10:41:31')),
            array('NewsItem' => array('id' => '2', 'title' => 'News 2', 'body' => 'This is some other piece of news', 'created' => '2009-05-04 9:00:00', 'modified' => '2009-05-05 12:34:56'))
        );
        print_r($results);
        $this->assertEqual($results, $expected);
    }   
}

?>

无论如何,我的问题是,当我在浏览器中运行测试套件时(转到http://localhost/test.php),测试用例运行器会尝试加载我的应用程序的布局(这很奇怪,因为我只是在测试模型)引用了另一个显然没有加载到测试数据库中的模型,我得到一个错误。

如果我删除 var $fixtures = array('app.newsitem') 我的 NewsItemTestCase 文件中的行,测试用例运行正常,但它没有加载固定装置(原因很明显)。

有什么想法、建议吗?老实说,我很难找到超过 3 个关于这个问题的教程。

【问题讨论】:

  • 请注意。我似乎通过使用 cake 的烘焙控制台实用程序重新烘焙模型和测试类来解决了这个问题。我看到的唯一变化是模型类正确(基于个人意见)现在位于 app/models/news_item.php

标签: unit-testing cakephp tdd cakephp-1.2


【解决方案1】:

这是很久以前的事了,但问题是命名约定,如果夹具被称为“NewsItemFixture”,则文件应该是 news_item_fixture,而不是 newsitem_fixture。如果你想要名为 newsitem_fixture 的文件,fixture 类应该是 NewsitemFixture。

所有其他文件也是如此,例如您那里的模型。

【讨论】:

  • 很抱歉挖掘了这个,但我目前遇到了同样的问题。我已经更新了我的命名以符合惯例,但仍然没有运气。如果您有时间看,我将不胜感激:stackoverflow.com/questions/7408936/…
  • 确保文件命名正确(包括测试和固定装置)的一种简单方法是使用BakeShell,尽管它实际上是 2.x 及更高版本。
  • Cakes bake 早在 2.x 之前就已经存在了
猜你喜欢
  • 2010-12-26
  • 1970-01-01
  • 2014-12-31
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 2012-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多