【问题标题】:Workaround for CakePHP tests with enums?使用枚举进行 CakePHP 测试的解决方法?
【发布时间】:2014-04-25 21:06:56
【问题描述】:

我尝试为 CakePHP 项目创建单元测试。创建固定装置和一些测试后,我遇到了问题:

警告:列类型 enum('on','off') 不存在于 /app/cake/2.4.7/Cake/Model/Datasource/DboSource.php 在第 3081 行

...

应用程序错误:调用处理程序方法异常“PDOException”与 消息'SQLSTATE [42S22]:找不到列:1054 未知列 '字段列表'中的'状态' /app/cake/2.4.7/Cake/Model/Datasource/DboSource.php:2923

我知道 CakePHP 不支持枚举,但我无法更改数据类型。是否有任何解决方法可以让单元测试使用枚举运行?

【问题讨论】:

  • 您不能使用文本字段创建您的灯具吗?
  • 我还没试过。我有一个有 33 列的表,我使用 public $import = 'MyModel';。手动定义所有列将非常繁琐:(。
  • 如果单元测试在枚举上失败,为什么应用程序没有?
  • 我认为是因为应用程序将数据库与现有表一起使用,并且单元测试尝试读取现有模式、创建表、插入一些数据然后运行测试。因此,错误发生在检索现有模式和创建表的过程中。
  • 我猜,单元测试在创建表时省略了枚举列。

标签: unit-testing cakephp testing enums cakephp-2.4


【解决方案1】:

我遇到了同样的问题。为了解决这个问题,我创建了一个子类来扩展 CakeTestFixture 类并覆盖表的创建以将所有枚举字段重新映射到字符串。

<?php

class MyTestFixture extends CakeTestFixture {

  /**
   * Maps enum fields in the database to strings with a length of 64
   */
  function create(&$db) {
    foreach($this->fields as $name => &$field) {
      if( strstr($field['type'], "enum") !== false ) {
        $field['type'] = 'string';
        $field['length'] = 64;
      }
    }
    parent::create($db);
  }
}

要使用它,只需在您的夹具中扩展这个类,而不是 CakeTestFixture。

<?php

App::uses('MyTestFixture', 'WhereverYouPutIt');

class MyTableFixture extends MyTestFixture {
    public $import = array('model' => 'MyTable');
}

【讨论】:

  • 为什么在 create(&$db) 中引用?至少这会导致 php 抱怨它与父级的 create($db) 声明不匹配。
猜你喜欢
  • 2020-01-08
  • 1970-01-01
  • 2010-11-07
  • 1970-01-01
  • 1970-01-01
  • 2022-01-18
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
相关资源
最近更新 更多