2014-10-29 144 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用于测试你的代码。因为现在它使用默认数据库。