2009-12-11 65 views
3

所以我正在使用CakePHP v1.2.5。在我目前的項目中,我決定開始編寫測試代碼功能(yay TDD)。儘管我在夾具加載時遇到了問題。cakephp單元測試模型,燈具問題

爲了幫助這個過程,我將描述我的代碼(現在非常簡單)。我的模型定義,像這樣

// 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)運行測試套件,測試用例亞軍嘗試加載我的應用程序的佈局(這是奇怪的因爲我只是測試模型),它引用另一個模型,顯然沒有加載到測試數據庫中,我得到一個錯誤。

如果我從我的NewsItemTestCase文件中刪除 var $fixtures = array('app.newsitem')行,測試用例運行正常,但它不會加載fixtures(出於顯而易見的原因)。

任何想法,建議?說實話,我在這個問題上找到3個以上的教程有點麻煩。

+0

只是一個領導。我似乎已經通過使用Cake的烘焙控制檯實用程序重新烘焙模型和測試類來解決問題。只有改變我看到的是模型類是正確的(根據個人意見)現在在app/models/news_item.php – 2009-12-11 02:47:05

回答

2

這是很久以前,但問題是命名約定,如果夾具被稱爲「NewsItemFixture」,文件應該是news_item_fixture,而不是newsitem_fixture。如果您想要名爲newsitem_fixture的文件夾具類應該是NewsitemFixture。

對於所有其他文件也是如此,例如您在那裏的模型。

+0

對不起,挖掘它,但我目前遇到同樣的問題。我已更新我的命名以符合慣例,但仍然沒有運氣。如果你有時間看,我會很感激: http://stackoverflow.com/questions/7408936/cakephp-unit-testing-fixture-name-conventions-argh – Zetaphor 2011-09-14 13:40:07

+0

一個簡單的方法來確保你的文件命名正確(包括測試和固件)是使用[BakeShell](http://book.cakephp.org/2.0/en/console-and-shells/code-generation-with-bake.html),雖然這真的是2.x和以上。 – beporter 2014-09-12 20:09:19

+0

蛋糕烘焙已經在2.x之前很久 – dogmatic69 2014-09-12 21:46:26