2014-10-29 131 views
0

我嘗試使用CakePhP 2.3和PHPUnit 2.7進行單元測試。我想在客戶的控制器中測試索引功能。 在我的控制,我有:CakePhP和PHPUnit單元測試

public function index() { 

    $this->Customer->recursive = -1; 
    $data = $this->paginate('Customer', array('Customer.status'=>'active')); 
    $this->set('customers', $data); 

} 

我試圖按照book.cakephp.org的例子,所以我創建夾具類中,我真的導入客戶模式和所有記錄。

class CustomerFixture extends CakeTestFixture{ 

    public $import = array('model' => 'Customer', 'records' => true); 

} 

最後我的測試類是這樣的:

class CustomersControllerTest extends ControllerTestCase { 

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

    public function testIndex() { 

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

當我運行我的測試,我有以下錯誤:

數據庫錯誤 錯誤:SQLSTATE [23000]:完整性約束違規:1062重複輸入'8'爲鍵'PRIMARY'

你有什麼想法可以是什麼問題?

回答

1

在你的app/Config文件夾的database.php中,你必須添加一個$ test變量。

例如

class DATABASE_CONFIG { 

    public $default = array(
     'datasource' => 'Database/Mysql', 
     'persistent' => true, 
     'host' => 'localhost', 
     'port' => 3306, 
     'login' => 'root', 
     'password' => 'xxxx', 
     'database' => 'mydatabase', 
     'encoding' => 'utf8' 
    ); 

    public $test = array(
     'datasource' => 'Database/Mysql', 
     'persistent' => false, 
     'host' => 'localhost', 
     'port' => 3306, 
     'login' => 'root', 
     'password' => 'xxxx', 
     'database' => 'mydatabase_test', 
     'encoding' => 'utf8' 
    ); 

} 

那麼你的單元測試將使用mydatabase_test用於測試你的代碼。因爲現在它使用默認數據庫。