【问题标题】:Unit-testing with CakePhP and PHPUnit使用 CakePhP 和 PHPUnit 进行单元测试
【发布时间】:2014-12-25 06:55:00
【问题描述】:

我正在尝试使用 CakePhP 2.3 和 PHPUnit 2.7 进行单元测试。我想在客户的控制器中测试索引功能。 在我的控制器中,我有:

public function index() {

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

}

我尝试按照 book.cakephp.org 中的示例进行操作,因此我创建了 Fixture 类,我将在其中导入 Customer 架构和所有记录。

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 键 'PRIMARY' 的重复条目 '8'

您有什么想法可能是什么问题吗?

【问题讨论】:

    标签: unit-testing cakephp phpunit cakephp-2.0


    【解决方案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 来测试您的代码。因为现在它使用的是默认数据库。

    【讨论】:

      猜你喜欢
      • 2017-08-14
      • 2013-09-13
      • 2023-03-06
      • 2017-08-16
      • 2012-07-28
      • 2014-02-12
      • 2011-06-06
      • 2012-03-26
      • 2011-05-30
      相关资源
      最近更新 更多