DataSource如何在cakephp 2中测试

时间:2017-08-25 07:51:56

标签: php cakephp

我们有自定义DataSource并且想要测试在find方法执行等于未定制的方法之后验证数据。正如我所想,如果我们可以在测试代码中更改数据源,那将是可能的。我尝试了很多情况,但是我无法使它发挥作用。

 public $default = [
    'datasource' => 'CustomPostgres',
    'persistent' => false,
    'host' => 'localhost',
    'port' => '5432',
    'login' => 'hoge',
    'password' => 'hogehoge',
    'database' => 'prod',
    'schema' => 'public',
    'prefix' => '',
    'encoding' => 'utf8'
];

public $test = [
    'datasource' => 'CustomPostgres',
    'persistent' => false,
    'host' => 'localhost',
    'port' => '5432',
    'login' => 'hoge',
    'password' => 'hogehoge',
    'database' => 'test_prod',
    'schema' => 'public',
    'prefix' => '',
    'encoding' => 'utf8'
];

public $old = [
    'datasource' => 'Database/Postgres',
    'persistent' => false,
    'host' => 'localhost',
    'port' => '5432',
    'login' => 'hoge',
    'password' => 'hogehoge',
    'database' => 'dev',
    'schema' => 'public',
    'prefix' => '',
    'encoding' => 'utf8'
];

public $test_old = [
    'datasource' => 'Database/Postgres',
    'persistent' => false,
    'host' => 'localhost',
    'port' => '5432',
    'login' => 'hoge',
    'password' => 'hogehoge',
    'database' => 'test_dev',
    'schema' => 'public',
    'prefix' => '',
    'encoding' => 'utf8'
];

//try1
$this->Model->setDataSource('test_old');
//try2
ConnectionManage::create('test_old',///);
//try3
////in fixture File and ClassRegistry:Init("Model")
$useDbConfig = "old";
////inner start::up
ClassRegistry:Init("Model");
//try4 extends model
ModelForOldSetting extends Model{
  $useDbConfig = "old";
}

以上代码不起作用,它总是发出错误说 MissingConnectionException:数据库连接“Postgres”在运行测试时丢失或无法创建,但在没有测试的情况下设置运行本地浏览器的默认数据源Database / Postgres时,它可以正常工作。

所以,我真的很困惑为什么数据库连接“Postgres”丢失了。任何想法都让我感激他们。

1 个答案:

答案 0 :(得分:0)

我终于通过外部database.php文件发现了令人恼火和愚蠢的恼人代码覆盖了数据源的设置。以下代码在适当的设置后工作正常。

ModelForOldSetting extends Model{
  $useDbConfig = "dev";
  $useTables = "models";
}

ClassRegistry:Init("ModelForOldSetting");
$model = $this->getMockForModel('ModelForOldSetting');