2014-03-31 110 views
0

我是CakePHP的單元測試部分的新手。現在沒有比現在更好的學習時間了。CakePHP單元測試控制器返回未定義的變量

我已準備好通過網絡上的所有文檔和大量教程。在完成一些更基本的單元測試期間,我碰到了一個障礙。

我的控制器:

class TestsController extends AppController { 

    public $components = array('RequestHandler', 'Security'); 

    public $helpers = array('Js'); 

    public $uses = array('Tests'); 

    public function beforeFilter() { 
     $this->layout = 'admin'; 
     parent::beforeFilter(); 
    } 

/** 
* Returns database values of all tests that have been created. 
* 
*/ 
    public function index() { 
     if ($this->request->is('requested')) { 
      return $tests; 
     } 
     $this->paginate = array(
      'fields' => array('id', 'name', 'email', 'access_token', 'access_token_begins', 
       'filesizelimit', 'related_files', 'access_token_expires'), 
      'limit' => 10, 
      'order' => array(
       'created' => 'desc' 
     )); 
     $this->set('tests', $this->paginate('Test')); 
    } 

我的控制器檢測程序是這樣的:

class TestsControllerTest extends ControllerTestCase { 

    public $fixtures = array('app.test'); 

    public function testIndex() { 

     $result = $this->testAction('tests/index'); 
     debug($result); 
    } 
    } 

我測試的輸出是:

PHPUNIT_FRAMEWORK_ERROR_NOTICE 
Undefined variable: tests 
Test case: testsControllerTest(testIndex) 

唯一可行的解​​決錯誤我我正在接受的是,可能在測試控制器實際運行之前需要進行身份驗證?

這是CakePHP文檔指南中的一個非常簡單的示例,但我收到並且未定義變量錯誤。任何幫助是極大的讚賞。

+0

您的索引視圖中是否有一個名爲'$ tests'的變量? –

+0

是的,我確實有一個名爲$ tests的變量。任何其他想法? – lockdown

+0

您是否將它設置爲測試/索引操作中的視圖? –

回答

0

我已經設法回答我自己的問題。

$tests變量是不確定的,因爲控制器中的if語句:

public function index() { 
    if ($this->request->is('requested')) { 
     return $tests; 
    } 
    $this->paginate = array(
     'fields' => array('id', 'name', 'email', 'access_token', 'access_token_begins', 
      'filesizelimit', 'related_files', 'access_token_expires'), 
     'limit' => 10, 
     'order' => array(
      'created' => 'desc' 
    )); 
    $this->set('tests', $this->paginate('Test')); 
} 

運行應用程序時,這種說法並沒有撞到,但運行測試時它的作用。在這個給定的函數中沒有必要使用IF語句,因此我現在解決了未定義變量的錯誤。